Geocoding & Reverse Geocoding in Google Map Javascript API

Geocoding is a technique of Google Map API which is used to get complete information about an address like its geographic coordinates (latitude, longitude), its city, state, postal_code, country etc. In javascript, we can just simply use below code to get geographic coordinates of any location :

<script type=”text/javascript”>
var geocoder_obj = new google.maps.Geocoder();

geocoder_obj .geocoder.geocode({
“address”: {your_address}
}, function(results, status) {

if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat(); //Latitude of location
var longitude = results[0].geometry.location.lng(); //Longitude of location
}else{
alert(status);
}

});
</script>

 

Reverse Geocoding is a technique in which one can get address and other address information of a location by providing its geographic coordinates (latitude, langitude) or place id. We can just use below code for it :

<script type=”text/javascript”>
var geocoder_obj = new google.maps.Geocoder();

geocoder_obj .geocoder.geocode({
“latLng”: new google.maps.LatLng({your_location_latitude}, {your_location_longitude})
}, function(results, status) {

if (status == google.maps.GeocoderStatus.OK) {
//Complete address
var complete_address = results[0].formatted_address;
var place = results[0];
for (var i = 0; i < place.address_components.length; ++i) {
var component = place.address_components[i];
jQuery.each(component.types, function(index, value) {
if (value == “administrative_area_level_1”) {
alert(‘administrative_area_level_1 : ‘+value);
}else if (value == “locality”) {
alert(‘locality : ‘+value);
}else if (value == “postal_code”) {
alert(‘postal_code : ‘+value);
}else if (value == “country”) {
alert(‘country : ‘+value);
}
});
}
}else{
alert(status);
}

});
</script>

Thus, using above two techniques of Google Map API i.e. geocoding and reverse geocoding, we can easily get all address information of any place.

Leave a Reply