This is a quick and easy way to find out latitude and longitude information of a specific city in PHP, using the Google Maps API.
This API is pretty comprehensive, as you would expect, and as usual it returns data in JSON format. As an example, suppose you want to get location information about London, UK. The query URL you need to use is the following:
If you look at the results in your browser, this is an extract of the information provided:
As you can see, we can also get latitude and longitude information (you can see this info at the bottom of the screenshot). So at this point, getting these two pieces of info in PHP becomes easy.
$city = 'London'; #Find latitude and longitude $url = "http://maps.googleapis.com/maps/api/geocode/json?address=$city"; $json_data = file_get_contents($url); $result = json_decode($json_data, TRUE); $latitude = $result['results']['geometry']['location']['lat']; $longitude = $result['results']['geometry']['location']['lng'];
Using cURL makes this even easier, and it’s only a matter of understanding the structure of the JSON results array to navigate to the information you are interested in.