In this article I will explain how to get the address location from Latitude and Longitude using the Google Maps Geocoding API.
I will explain two different ways of using the process of Reverse Geocoding using the Google Maps Geocoding API.
Direct Usage
Here I’ll pass the value of Latitude and Longitude directly from TextBoxes to the Google Maps Geocoding API and it will return me the address of the location.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
Latitude:
<input type="text" id="txtLatitude" value="18.92488028662047" />
Latitude:
<input type="text" id="txtLongitude" value="72.8232192993164" />
<input type="button" value="Get Address" onclick="GetAddress()" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function GetAddress() {
var lat = parseFloat(document.getElementById("txtLatitude").value);
var lng = parseFloat(document.getElementById("txtLongitude").value);
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert("Location: " + results[1].formatted_address);
}
}
});
}
</script>
</body>
</html>
Using Maps
Here I’ll be determining the coordinates of the location when user clicks on the Google Map and then these coordinates will be used to determine the address of the location using the Google Maps Geocoding API.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(18.9300, 72.8200),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
var latlng = new google.maps.LatLng(e.latLng.lat(), e.latLng.lng());
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert("Location: " + results[1].formatted_address + "\r\nLatitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
}
}
});
});
}
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
</body>
</html>
Demo
Downloads