10

I have Postcode in my large database, which contains values like SL5 9JH, LU1 3TQ etc.

Now when I am pasting above postcode to maps.google.com it's pointing to a perfect location..

My requirement is like I want to pass post codes to maps.google.com and it should return a related latitude and longitude of that pointed location, that I want to store in my database.

So, most probably there should be some javascript for that... If anybody have another idea regarding that please provide it..

Thanks in advance...

Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
Nirmal
  • 4,789
  • 13
  • 72
  • 114

6 Answers6

14

A quick note for those finding this SO answer. The answer by Daniel Vassallo uses the Google Geocoding API V2 which has now been deprecated. The new v3 API uses a request format like this:

http://maps.googleapis.com/maps/api/geocode/output?parameters

An example for a postcode lookup, returning the data in JSON format is:

http://maps.googleapis.com/maps/api/geocode/json?address=SL59JH,+UK&sensor=false

This returns a JSON array that includes the lat and long in results->geometry->location->lat and results->geometry->location->lng

Example response:

{
 "results" : [
  {
     "address_components" : [
        {
           "long_name" : "SL5 9JH",
           "short_name" : "SL5 9JH",
           "types" : [ "postal_code" ]
        },
        {
           "long_name" : "Windsor and Maidenhead",
           "short_name" : "Windsor and Maidenhead",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "United Kingdom",
           "short_name" : "GB",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "Ascot",
           "short_name" : "Ascot",
           "types" : [ "postal_town" ]
        }
     ],
     "formatted_address" : "Ascot, Windsor and Maidenhead SL5 9JH, UK",
     "geometry" : {
        "bounds" : {
           "northeast" : {
              "lat" : 51.39655490000001,
              "lng" : -0.66024660
           },
           "southwest" : {
              "lat" : 51.39457330,
              "lng" : -0.6624574999999999
           }
        },
        "location" : {
           "lat" : 51.39539040,
           "lng" : -0.66096740
        },
        "location_type" : "APPROXIMATE",
        "viewport" : {
           "northeast" : {
              "lat" : 51.39691308029150,
              "lng" : -0.6600030697084980
           },
           "southwest" : {
              "lat" : 51.39421511970851,
              "lng" : -0.6627010302915021
           }
        }
     },
     "types" : [ "postal_code" ]
  }
],
"status" : "OK"
}

The API spec is available here: https://developers.google.com/maps/documentation/geocoding/

CharlesA
  • 4,260
  • 2
  • 25
  • 31
10

The technical term for the process you describe is called reverse geocoding. Google offers the The Google Geocoding Web Service New working Google Geocoding Link, where you can do reverse geocoding on the server side, instead of in JavaScript on the client-side.

For example, if you try the following URLs in your browser, you would get back the latitude and longitude of the postcode passed in the q parameter, in CSV format:

http://maps.google.com/maps/geo?q=SL59JH,+UK&output=csv&sensor=false

http://maps.google.com/maps/geo?q=LU13TQ,+UK&output=csv&sensor=false

This is how you would be able to reverse geocode your postcodes in php, for example:

$url = 'http://maps.google.com/maps/geo?q=SL59JH,+UK&output=csv&sensor=false';

$data = @file_get_contents($url);

$result = explode(",", $data);

echo $result[0]; // status code
echo $result[1]; // accuracy
echo $result[2]; // latitude
echo $result[3]; // longitude

Note that as Pekka suggested in another answer, the Google Maps API Terms of Use seem to prohibit the storage of the results, unless the store acts as a cache for data that will used in Google Maps. You may want to get in touch with Google and enquire on the Google Maps API Premier to have more flexible terms of use for your geocoding requirements.

Community
  • 1
  • 1
Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
  • @Daniel... Thanks a lot for your feedback.. I will work out with your given solutions and will get back to you... – Nirmal Apr 12 '10 at 12:26
  • Is this still working as using the above examples in my browser I get back 610,0,0,0. Doesn't matter what postcode I sample, always 610,0,0,0? – QFDev Oct 10 '13 at 08:39
  • I think this is because the examples in this answer use an old version of the maps API. A new example would be like this: http://maps.googleapis.com/maps/api/geocode/json?address=SL59JH,+UK&sensor=false. Obviously the query to extract the lat/lng would need to be changed as the output is now returning JSON rather than CSV. – Dan Mar 13 '14 at 10:59
  • "Reverse geocoding is lat-long to a readable address" so Daniel Vassallo process is geocoding. – Moji Feb 08 '16 at 16:10
9

The Ordnance Survey have released the postcode locations on a Creative Commons licence (CC-BY v3, IIRC). It would be a lot less hassle (and a lot clearer legally) to use that instead.

There's even a version with WGS84 (a.k.a. GPS) coordinates mirrored by mySociety

Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
  • +1 a link to the ordnance survey data dump would also be nice if you had it handy. – Pekka Apr 12 '10 at 20:21
  • its link after link after link, cant see no 20mb zip file like it promises on the first page. after 5 minutes looking i give up. – brux May 01 '14 at 15:12
  • @brux from the link I gave, you tick the download box for the "Code-Point® Open" product, go to next, fill in the form, and wait for the email with the download link. Simple as that. – Rowland Shaw May 01 '14 at 16:11
3

The Google Geocoding API does that, although if I remember correctly, their terms of service forbid local storage of the geocoding results.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • I did an application once based on that and I don't remember having this limitation. I think is against logic not to save the results as they will not change in time and thus save a future ping to google. – Elzo Valugi Apr 15 '10 at 09:44
  • 1
    @Elzo you're right, it's allowed to "temporarily" cache the results if used in a Google maps app: 10.3 http://code.google.com/intl/en-EN/apis/maps/terms.html – Pekka Apr 15 '10 at 09:46
  • Does anyone know if theres an https version for getting long and latt by post code? – AngularM Jan 11 '16 at 13:39
  • same as the above post, just change http to https https://maps.googleapis.com/maps/api/geocode/json?address=SL59JH,+UK&sensor=false – Wesley Stam Nov 17 '16 at 07:41
1

I know this is an old question, but just chipping in here with how I managed to achieve the same thing (in PHP, but should be fairly simple):

  1. I had a database of thousands of differently formatted postcodes. I cleaned each and every one of them up, uniformly, with this function and batch updates:

    function clean_postcode($postcode)
    {
        $out = preg_replace("/[^a-zA-Z0-9]/", '',strtoupper($postcode));
    
        if(strlen($out)>3) 
        {
            $out = substr($out, 0, (strlen($out) -3)).' '.substr($out, -3);
        }
    
        return $out;
    }
    
  2. Now that all postcodes are formatted uniformly, I downloaded and imported the Ordnance Survey's Code-Point data set (free) - https://www.ordnancesurvey.co.uk/opendatadownload/products.html

  3. I imported all their CSVs into my database in a separate codepoint table. From each CSV I imported the postcode, and the Eastings and Northings values.

  4. I ran the clean_postcode() function again in batch on all the Ordnance Survey data in my DB. About 50% of the postcodes have spaces in, and 50% don't - after this they were uniformly set.

  5. I ran the following PHP script on each and every postcode in the codepoint table and saved the Latitude and Longitude values returned into this table: http://bramp.net/blog/os-easting-northing-to-lat-long

  6. All done! You can now match up and pull a Lat/Lon value based on well-formatted postcodes.

Further reading: http://www.deepbluesky.com/blog/-/converting-os-coodinates-into-longitude-latitude_7/

Jack
  • 9,615
  • 18
  • 72
  • 112
-1

Check out ALgolia places here. Super fast, Open source and MIT

Kumar
  • 449
  • 5
  • 7