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:

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 = "$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.


  1. Thanks.. works great..

  2. 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!

  3. Giving limit exceed error on api call please help

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2018 Daniel's TechBlog

Theme by Anders NorénUp ↑

%d bloggers like this: