Watch user location using Geolocation API

If you are developing real time user location application, then you may want to use The Geolocation API instead of third party services. The Geolocation API supports all modern web browsers. You don't need to write lengthy code.

The Geolocation API in Javscript is used to get user location. For privacy reason, user is asked permission to share user's location. If the user grant permission, you will get user location details object.

In previous article, we have shared you how you can get user location using Geolocation API. In this article, we will share how you can watch for user location. 

navigator.geolocation.watchPosition() method

The navigator.geolocation.watchPosition() method registers a handler function that will be called automatically each time when user device location changes, and it will returns the updated location.


navigator.geolocation.watchPosition(successFunction, errorFunction, options);


successFunction  when user grants permission 
errorFunction Optional which calls if error occurs
options Optional configuration options for getting location

The method accepts three parameters, 

// success function
function success (position) {

// error function
function error (error) {

var options = {
    enableHighAccuracy: true

const watchId = navigator.geolocation.watchPosition(success, error, options);

navigator.geolocation.clearWatch() method

navigator.geolocation.clearWatch() method is used to stop watching user location handling started in navigator.geolocation.watchPosition() method.




watchId Id of the geolocation.watchPosition() method.

Here is the full example rendering user location in Google Maps:

<!DOCTYPE html>
    <meta charset="utf-8">
    <title>Google Maps</title>
        #map {
            height: 400px;
            width: 600px;
    <div id="map"></div>
    <button onclick="stopWatch()">Stop</button>
    <script async defer src=""></script>
    <script type="text/javascript">
        const watchId = navigator.geolocation.watchPosition(
            position => initMap(position)

        function stopWatch() {

        function initMap(position) {
            const { latitude, longitude } = position.coords;

            const center = {lat: latitude, lng: longitude};
            const options = {zoom: 15, scaleControl: true, center: center};
            map = new google.maps.Map(document.getElementById('map'), options);
            const point = {lat: latitude, lng: longitude};

            // create marker
            var marker = new google.maps.Marker({position: point, map: map});

This will keep eye on user location. When user location updates, the watchPosition will send new location to Google Maps and Google Maps will update location in map.