Geolocation

The Geolocation API lets authorized Web applications to access the location data provided by the device - obtained using either GPS or from the network environment. Apart from the one-off location query, it gives a way for the app to be notified about the location changes.

API glimpse

navigator.geolocation.getCurrentLocation(callback)
Runs one-off query for location with coordinates, accuracy, altitude & speed, if available.
navigator.geolocation.watchLocation(callback)
Sets up observing for location changes, invoking callback for every change.

Live Demo

  • var target = document.getElementById('target');
    var watchId;
    
    function appendLocation(location, verb) {
      verb = verb || 'updated';
      var newLocation = document.createElement('p');
      newLocation.innerHTML = 'Location ' + verb + ': <a href="https://maps.google.com/maps?&z=15&q=' + location.coords.latitude + '+' + location.coords.longitude + '&ll=' + location.coords.latitude + '+' + location.coords.longitude + '" target="_blank">' + location.coords.latitude + ', ' + location.coords.longitude + '</a>';
      target.appendChild(newLocation);
    }
    
    if ('geolocation' in navigator) {
      document.getElementById('askButton').addEventListener('click', function () {
        navigator.geolocation.getCurrentPosition(function (location) {
          appendLocation(location, 'fetched');
        });
        watchId = navigator.geolocation.watchPosition(appendLocation);
      });
    } else {
      target.innerText = 'Geolocation API not supported.';
    }
  • <button class="btn btn-default" id="askButton">Ask for location</button>
    
    <div id="target"></div>

Resources