08 December 2008

Calculate Latitude-Longitude using Google API

Google API provide a nifty tool for calculations the latitude and longitude of the place based upon the address. These geographical data can be used for Google Map Generation. Make sure that you read the Google Maps API documents before starting.

//code for using google maps to calculate latitude and longitude dynamically

<script type="text/javascript" language="javascript">

var geocoder;
var map;
var xmlHttp;

// this function has to be called when page loads..FOR IE facing Operation aborted problem call this function at end of page before </body> tag & make sure google map version is 2.118 or greater

function load()
{
map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(0,0), 8);//temporay center
geocoder = new GClientGeocoder();
}

//call this function after validations have been performed and true
function showAddress(address)
{
var flag_addr1=0;
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
if (geocoder)
{

geocoder.getLatLng(address, function(point)
{

if (!point)
{
alert("Address " +address+" not found");
flag_addr1 = 0;

}
else
{

//hidden fields on the webform , inside a form(postback values used for updating database)
document.getElementById("lat").value = point.lat().toFixed(5);
document.getElementById("lng").value = point.lng().toFixed(5);
flag_addr1 = 1;
//setTimeout("document.frm_add_place.submit()",2000);

document.frm_add_place.submit(); //used to submit form only when correct address is found

}
}
);
}

}
</script>

Note: You can call the showAddress() JavaScript function before a user submits a form and pass values entered by user like state,city,zip code, street address.
The values in the hidden fields lat,lng can be used to store in database for dynamic map generation.

No comments: