Google Maps API Tutorial Google Maps API Tutorial
Back to Home Page

Geocoding Example for Google Maps API

View Example


Notes

The key is to use google.maps.Geocoder class and geocoder.geocode() function.

Source Code

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Google Map API V3: Geocoding</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<style type="text/css">
body { margin: 20; padding: 20 }
</style>
<script type="text/javascript">
function submit() {
	var address = document.getElementById('address').value;
	geocoding(address);
}

function geocoding(address) {
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode( { 'address': address}, function(results, status) {
  		if (status == google.maps.GeocoderStatus.OK) {
			var lng = results[0].geometry.location.lng();
      		var lat = results[0].geometry.location.lat();
      		var geocodingresult = document.getElementById('geocodingresult');
      		geocodingresult.innerHTML = "The geocoding result of address " + address + " is: latitude " + lat + ", longitude " + lng;
 		} 
 		else {
 			var geocodingresult = document.getElementById('geocodingresult');
      		geocodingresult.innerHTML = "Error result when geocoding the address " + address;
  		}
	});
}

</script>
</head>
<body>

<center>
Please input an address:
<input type="text" name="address" id="address" size="40">
<button onclick="submit();">Go</button>
<div id="geocodingresult"></div>
</center>

</body>
</html>