Saturday, January 14, 2012

How to get the current location of the user by using Geolocation API in HTML5?

In my previous article we discussed how to detect the Geolocation API availability in our browser. This article provides a sample showing how to use the geolocation object’s getCurrentPosition method to get the current location of the user and display it in a webpage. The getCurrentPosition method initiates an asynchronous request for location information and returns immediately. If the request completes successfully, a success callback that we implement to receive location data is invoked.

The below code snippet shows how to use the getCurrentPosition method to get the latitude and longitude of the user.

using getCurrentPosition() of Geolocation API:

function requestPosition() {
if (nav == null) {
nav = window.navigator;
}
if (nav != null) {
var geoloc = nav.geolocation;
if (geoloc != null) {
geoloc.getCurrentPosition(successCallback);
}
else {
alert("Geolocation API is not supported in your browser");
}
}
else {
alert("Navigator is not found");
}
}

When the getCurrentPosition gets the current position, it call's the function successCallback() and updates the textboxes in the page by using the latitude and longitude coordinates.

using successCallback():

function successCallback(position)
{
setLocation(position.coords.latitude, "latitude");
setLocation(position.coords.longitude, "longitude");
}

Example:

<!DOCTYPE html> 
<html>
<head>
<title>Geolocation API Example</title>
<script type="text/javascript">
function setLocation(val, e) {
    document.getElementById(e).value = val;
}
var nav = null;
function requestPosition() {
  if (nav == null) {
      nav = window.navigator;
  }
  if (nav != null) {
      var geoloc = nav.geolocation;
      if (geoloc != null) {
          geoloc.getCurrentPosition(successCallback);
      }
      else {
          alert("Geolocation API is not supported in your browser");
      }
  }
  else {
      alert("Navigator is not found");
  }
}
function successCallback(position)
{
   setLocation(position.coords.latitude, "latitude");
   setLocation(position.coords.longitude, "longitude");
}
</script>
</head>
<body>
<label for="latitude">Latitude: </label><input id="latitude" /><br />
<label for="longitude">Longitude: </label><input id="longitude" /> <br />
<input type="button" onclick="requestPosition()" value="Get Latitude and Longitude"  />
</body>
</html>

Sample Output:



How to get the current location of the user by using Geolocation API in HTML5

Demo:



0 comments:

Post a Comment

Subscribe via Email