Wednesday, 8 June 2011

Geolocation API & Google maps API combined

Using HTML Geolocation API with google V3 maps API to identify current client address/country. It can be used for applications that provide location dependent information. You can double click the file to execute and see your current address. Save the sample.html on your local file system and give it a try.

Important:
  • It is tested on FF using a wired LAN connection
  • It throws an error if used from a wireless network adapter and didn't have time to investigate why.

sample.html
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width"/>
<title>Identify My Location</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

<script type="text/javascript">
var geocoder;
var lat;
var lng;
var latlng;
var myaddress="";

function init(){
geocoder= new google.maps.Geocoder();
getLocation();
}

function getLocation(){
var gps = navigator.geolocation;
var position;
if (gps){
position=gps.getCurrentPosition(gpsCallBack,function (error){alert ("error");});
} else {
}
}

function gpsCallBack(position){
if (position){
lat = position.coords.latitude;
lng = position.coords.longitude;
latlng=new google.maps.LatLng(lat,lng);
if(geocoder){
geocoder.geocode({'latLng': latlng},storeAddress);
}
}

}

function storeAddress(results,status){
if(status == google.maps.GeocoderStatus.OK){
if (results[0]) {
myaddress="";
var addresses=results[0].address_components;
for(i=0;i<addresses.length;i++){
if(i==0){
myaddress=addresses[i].long_name;
}else{
myaddress=myaddress+" - "+addresses[i].long_name;
}

}
document.getElementById("myaddress").innerHTML=myaddress;
} else {
alert("No results found");
}
}else{
alert(status);
}
}

</script>
</head>
<body onLoad="init()">
<div id="myaddress">
</div>
</body>
</html>

No comments:

Post a Comment