Find Longitude And Latitude Of PostCode or ZipCode Using Google Maps And PHP

4 September, 2008 | PHP

Converting from PostCode to map reference is far from accurate, but it can be done using the Google Maps API. You can get a Google Maps API key from Google by just asking for it, although you are limited to a certain number of requests each day.

Google Maps usually works through JavaScript, but it is possible to ask Google 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 get Google to return the data in JSON you must pass the parameter "output=json" in your query string.

The following function can take a postal code and convert it into 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($query);
 // if data returned
 if($data){
  // convert into readable format
  $data = json_decode($data[0]);
  $long = $data->Placemark[0]->Point->coordinates[0];
  $lat = $data->Placemark[0]->Point->coordinates[1];
  return array('Latitude'=>$lat,'Longitude'=>$long);
 }else{
  return false;
 }
}

The function can be used in the following way. To keep with the theme, the following two postal codes are two UK and USA office locations of Google.

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

This produces the following output.

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

I have tried this with UK and USA postal codes, but it would be interesting to see if it works with any other codes. Also, the query currently looks at google.co.uk, but that is only because I am based in the UK. You should change this to the nearest Google domain, so if you are based in the US then change this to google.com.

Comments

Pingback from Converting UK PostCode To Longitude And Latitude With PHP | Talk In Code
Date: November 21, 2008, 2:03 pm

[...] coordinates. An alternative is to use a method that I have talked about previously in the post find longitude and latitude of PostCode or ZipCode using Google Maps And PHP, but that requires you to have a valid, working Google maps API key. this method is an alternative [...]

Write a comment