Monday, June 1, 2015

Finding Latitude and Longitude of a location

HTML5 supports geolocation which helps in finding current longitude and latitude. As this affects privacy, browser ask user if they want to allow the application to read the current location of user. The javascript code to get the current position is as follows:

<script type="text/javascript">

 var success = function(position){
   console.log(position);
  };


var error = function(error){      
    console.log(error);
  };

var option = {
   enableHighAccuracy: true,
   timeout: 1000,
   maximumAge: 0
};

if(navigator.geolocation){       navigator.geolocation.getCurrentPosition(success,error,option);
}

</script>

Read the code from the last block which checks if geolocation feature is enabled. If it is enabled, it calls getCurrentPosition method call. In case of success, success function is called. In case of failure error function is called. Option is the set of parameters passed to the getCurrentPosition function. 

If the function is successful, than in your browser console log, you should be able to see the position object printed as follows:

Geoposition {timestamp: 1433137332905, coords: Coordinates}
coords: Coordinates
accuracy: 78
altitude: null
altitudeAccuracy: null
heading: null
latitude: 18.8305556
longitude: 73.02897129999999
speed: null

It returns a host of parameters which can be used for different purpose. If you are interested in latitude and longitude than use the following format:

var latValue = position.coords.latitude;
var longValue = position.coords.longitude;

console.log("Latitude:" + latValue + "  Longitude:" + longValue);

No comments:

Post a Comment