• notice
  • Congratulations on the launch of the Sought Tech site

Find Longitude and Latitude of PostCode or ZipCode using Google Maps and PHP

Converting from PostCode to map reference is far from accurate, but it can be done using the Google Maps API. Although there is a limit to the number of requests you can make per day, you only need to ask to get a Google Maps API key from Google.

Google Maps usually works via JavaScript, but Google can be asked to return the data in JSON format and then use the PHP function json_decode() to decode the information into a usable array format. To make Google return data in JSON format, you must pass the parameter "output=json" in the query string.

The following function can take a zip code and convert it to longitude and latitude.


function getLatLong ($code) {
  $mapsApiKey = 'your-google-maps-api-key' ;
  $query = "http://maps.google.co.uk/maps/geo?q=" .urlencode($code). "&output=json&key=" .$mapsApiKey;
  $data = file_get_contents($query);
  // if data is returned
  if ($data){
    // convert to readable format
   $data = json_decode($data);
   $long = $data->Placemark[ 0 ]->Point->coordinates[ 0 ];
   $lat = $data->Placemark[ 0 ]->Point->coordinates[ 1 ];
    return array ( 'Latitude' =>$lat, 'Longitude' =>$long);
  } else {
    return false ;
  }
}


This function can be used as follows. In keeping with the theme, the following two postcodes are a Google address in the UK and a US office location.


print_r (getLatLong( 'SW1W 9TQ' )); 
print_r (getLatLong( '10011' ));


This will produce the following output.


Array
(
  [Latitude] => 51.489943
  [Longitude] => -0.154065
)
Array
(
  [Latitude] => 40.746497
  [Longitude] => -74.009447
)


I've tried it with UK and US postcodes, but it will be interesting to see if it works with any other postcodes. Also, the query is currently looking for google.co.uk, but only because I'm based in the UK. You should change it to the nearest Google domain, so if you are in the US you should change it to google.com.


Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+