I
I
Ivan2016-05-19 12:08:51
PHP
Ivan, 2016-05-19 12:08:51

Is it possible to get the name of the city from the given latitude and longitude coordinates?

Greetings!
There is an address field that is tied to the Google Maps API. The template displays the address as text and a map widget. It is possible to convert values ​​and the address field into width and longitude. We need the ability to separately display only the city, so as not to make a separate taxonomy.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Novikov, 2016-05-19
@SteelMonk

This is called geocoding .

I
Ivan, 2016-06-23
@SteelMonk

Perhaps someone will come in handy, I'll post the working code here.

$geo = ""; // указываем источник адреса, например значение поля, шорткод
$gmap_api = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&language=ru&address=".urlencode($geo); // обращаемся к API
$request = file_get_contents($gmap_api); // обрабатываем результат
$jsondata = json_decode($request, true); // декодируем данные json
foreach ($jsondata["results"] as $result) { // получаем то что нам нужно
foreach ($result["address_components"] as $address) {
        if (in_array("locality", $address["types"])) {
            $city = $address["long_name"];
        }
    }
}
return $city; // готово

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question