Getting the Current Location

This topic provides a sample showing how to use the geolocation object’s getCurrentPosition method to get the current location 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 you implement to receive location data is invoked.

The following example shows how to call getCurrentPosition and handle the incoming position data using a callback. When the user clicks the Get Latitude and Longitude button in the example, the example's requestPosition function is called, which checks that the geolocation object is available before it calls getCurrentPosition. When the position is obtained, the callback function updates the text boxes in the page by using the latitude and longitude coordinates.

<!DOCTYPE html>  
<html>
<head>
<title>Geolocation API Example</title>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<script type="text/javascript">

function setText(val, e) {
    document.getElementById(e).value = val;
}

function insertText(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 not supported");
      }
  }
  else {
      alert("Navigator not found");
  }
}



function successCallback(position)
{
   setText(position.coords.latitude, "latitude");
   setText(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>

Important  

Because the success callback is invoked asynchronously, it is not possible to predict how quickly it may be invoked. If your callback is invoked before page elements it attempts to access have been loaded, your webpage won't function as expected. One way to avoid this problem is to make the call to getCurrentPosition within a function that is called after the page has finished loading.

 

Handling Errors

How to Create a Location-Aware Webpage

Specifying the Time-out Duration

Watching for Location Changes