Wednesday, January 12, 2011

User Location - Google MAP with JavaScript API V3 -Where am I in this world

This example will return the google map with the place where you are in-presently.
If the browser doesn't support the geolocation  methods  , it will display "hyderabad" by default.

Save this as a html file..and enjoy..




<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Know your location</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">


var initialLocation;
var hyderabad = new google.maps.LatLng(17.375278, 78.474444);
var browserSupportFlag =  new Boolean();


function initialize() {
  var myOptions = {
    zoom: 6,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  
  if(navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeolocation(browserSupportFlag);
    });
  
  } 
  
  function handleNoGeolocation(errorFlag) {
    if (errorFlag == true) {
      alert("Geolocation service failed.");
      initialLocation = hyderabad;
    } else {
      alert("Your browser doesn't support geolocation. We've placed you in Hyderabad.");
      initialLocation = hyderabad;
    }
    map.setCenter(initialLocation);
  }
}


</script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
</body>
</html>


The explanation about detailed understanding of each and every item in this source is explained in my previous "Hello World" blog on Google Maps.

The new thing here though is the 

navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      map.setCenter(initialLocation);

which is used to calculate the latitude longitude of the current position, and return the map of the same.

No comments:

Post a Comment

subversion video