Search code examples
google-mapsgeocodinggoogle-maps-api-2

Best way to geocode UK postcode with Google Maps API?


What is the most effective and accurate way to geocode a UK postcode? Using the built in geocode object results in massively blurred results (lots of postcodes returning just a general area).

Are there any free UK postcode geocoding services I can plug into via JavaScript?


Solution

  • Edit: To be clearer this uses the local search in google search api, not the google maps api to do the geocoding which is much more accurate.

    The best way is to use Google Search Api.

    If you get an api key and get it all setup: http://code.google.com/apis/ajaxsearch/

    var localSearch;
    var map;
    var icon;
    var addressMarkerOptions;
    google.load("search", "1");
    google.load("maps", "2");
    google.setOnLoadCallback(initialize);
    
    function initialize()
    {
      localSearch = new GlocalSearch();
      icon = new GIcon(G_DEFAULT_ICON);
      addressMarkerOptions = { icon:icon , draggable: false};
      map = new GMap2(document.getElementById("map"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      plotAddress("OX4 1FJ");
    }
    
    /**
    * This takes either a postcode or an address string
    *
    */
    function plotAddress(address)
    {
      localSearch.setSearchCompleteCallback(null, 
        function() {
    
          if (localSearch.results[0])
          {     
            var resultLat = localSearch.results[0].lat;
            var resultLng = localSearch.results[0].lng;
            var point = new GLatLng(resultLat,resultLng);
            var marker = new GMarker(point, addressMarkerOptions);
            map.addOverlay(marker);
            map.setCenter(point, 5, G_NORMAL_MAP);
          }
          else
          {
            alert('address not found');
          }
        });
    
      localSearch.execute(address + ", UK");
    }