How To Get Latitude And Longitude From City Name In PHP

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:

http://maps.googleapis.com/maps/api/geocode/json?address=London

If you look at the results in your browser, this is an extract of the information provided:

Screen Shot 2016-03-02 at 10.52.46

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'][0]['geometry']['location']['lat'];
$longitude = $result['results'][0]['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.

4 Comments

  1. Wow this is very nice! I thought from reading google’s docs that you had to use an api key but apparently not. Thanks for sharing this!

Leave a Reply

© 2017 Daniel's TechBlog

Theme by Anders NorénUp ↑

%d bloggers like this: