Here’s a handy few lines of PHP code for anyone wanting to get the latitude and longitude values from Google Maps API, based on the town, city or country location.
It took me a little while to get this to work. For some reason the various cURL and file_get_contents methods I saw online to get longitude and latitude values didn’t work for me and I needed to add ‘true’ to the ‘file_get_contents’ command for json_decode to work correctly. Hopefully this will help someone else out 🙂
<?php $url = "http://maps.google.com/maps/api/geocode/json?address=West+Bridgford&sensor=false®ion=UK"; $response = file_get_contents($url); $response = json_decode($response, true); //print_r($response); $lat = $response['results']['geometry']['location']['lat']; $long = $response['results']['geometry']['location']['lng']; echo "latitude: " . $lat . " longitude: " . $long; ?>
The http://maps.google.com/maps/api/geocode/json URL takes in 3 parameters: address (your main location), region (optional but can help with ambiguity) and sensor (indicates whether or not the request will come from a device with a locational sensor).
The print_r command commented out above is a useful way to work out the array structure that you need to drill down to. To get the longitude and latitude values, we need to drill down through 5 levels.