How to reverse geocode coordinates to get postal pincode using google map?

16,452

If you have a location (and a Google Maps API v3 map), reverse geocode the location. Process through the returned records for the postal_code (see this SO post for an example).

// assumes comma separated coordinates in a input element 
function codeLatLng() {
  var input = document.getElementById('latlng').value;
  var latlngStr = input.split(',', 2);
  var lat = parseFloat(latlngStr[0]);
  var lng = parseFloat(latlngStr[1]);
  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode({'latLng': latlng}, processRevGeocode);
}

// process the results
function processRevGeocode(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
       var result;
       if (results.length > 1)
          result = results[1];
       else
          result = results[0];
       if (result.geometry.viewport)
          map.fitBounds(result.geometry.viewport);
       else if (result.geometry.bounds)
          map.fitBounds(result.geometry.bounds);  
       else { 
          map.setCenter(result.geometry.location);
          map.setZoom(11);
       }
       if (marker && marker.setMap) marker.setMap(null);
       marker = new google.maps.Marker({
           position: result.geometry.location,
           map: map
       });
       infowindow.setContent(results[1].formatted_address);
       infowindow.open(map, marker);
       displayPostcode(results[0].address_components);

    } else {
      alert('Geocoder failed due to: ' + status);
    }
}

// displays the resulting post code in a div
function displayPostcode(address) {
  for (p = address.length-1; p >= 0; p--) {
    if (address[p].types.indexOf("postal_code") != -1) {
       document.getElementById('postcode').innerHTML= address[p].long_name;
    }
  }
}

Working example (displays a postcode from a geocoded address, reverse geocoded coordinates, or a click on the map)

Share:
16,452
ThinkFloyd
Author by

ThinkFloyd

Building teams and juggling between back-end & Front-end technologies

Updated on June 04, 2022

Comments

  • ThinkFloyd
    ThinkFloyd almost 2 years

    I am making an app which will take user's current location or his customized map marker to find out lat & long and then using those values I would like to know pincode(zipcode) of that area so that I can tell user whether goods can be delivered in that area or not.

    I have tried this : http://www.geonames.org/export/ws-overview.html but it doesn't have full data and whatever it has is not very accurate. Is there any other API which I can use to get such data?