Simple geocoding
HTML
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<body onload="initialize()">
<input id="address" type="text">
<input type="button" value="Geocode" onclick="codeAddress()">
<br/>
<label for="latitude">latitude</label>
<input id="latitude" type="text">
<br/>
<label for="longitude">longitude</label>
<input id="longitude" type="text">
<div id="map" style="height:300px; width: 480px"></div>
JavaScript
var geocoder;
var map;
function initialize()
{
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map"),
{
zoom: 8,
center: new google.maps.LatLng(22.7964,79.5410),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function codeAddress()
{
var addrInput = document.getElementById("address"),
latInput = document.getElementById("latitude"),
lngInput = document.getElementById("longitude");
latInput.value = "";
lngInput.value = "";
geocoder.geocode( { 'address': address.value},
function(results, status) { //nothing in this block is run until the results are ready
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker(
{
map: map,
position: results[0].geometry.location
});
latInput.value = results[0].geometry.location.lat();
lngInput.value = results[0].geometry.location.lng();
//this is called after the results are ready, and the inputs have been set
isResults("Inside callback");
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
//code out here is running asynchronously with the geocoding. We would expect
//for it to return first, BEFORE results are ready
isResults("Outside callback");
}
function isResults(where) {
var resultsAvail = false;
if(document.getElementById('latitude').value &&
document.getElementById('longitude').value) {
resultsAvail = true;
}
alert(where + ". Are results available? " + resultsAvail);
}