Search code examples
javascriptjquerygeolocationprogressive-web-apps

Why the location is being repeated on my PWA with JavaScript?


I have a problem to get the location of my PWA's users. The location that is being taken are repeated and is not being updated.

$("#storeLocation").click(function () {
  navigator.geolocation.getCurrentPosition(
    function (e) {
      a = e.coords.latitude + "," + e.coords.longitude; 

      // HERE I STORE THE COORDS IN MY DATABASE
    },
    { enableHighAccuracy: true, timeout: Infinity, maximumAge: 0 }
  );
});

The button is working because I could see that when I click on it is storing the location, but is storing always the same location.


Solution

  • If you want to continually monitor the user's location, use the Geolocation API method, watchPosition(). It works in the same way, except it will fire multiple times as the location of the user changes, or gets more accurate.

    $("#storeLocation").click(() => {
      const posOpts = { enableHighAccuracy: true, timeout: Infinity, maximumAge: 0 };
      navigator.geolocation.watchPosition((e) => {
        const position = a = e.coords.latitude + "," + e.coords.longitude;
        // Store position here
      }, posOpts);
    });