Sinan Noureddine Sinan Noureddine - 19 days ago 9
HTML Question

Check if browser's location turned on Only once

I'm using navigator.geolocation.watchPosition function to check if the browser's location is on or not. But this function is getting called more than once (without page load). For example if i switch to another tab and go back to the page's tab it gets called.

My code is

<script>

navigator.geolocation.watchPosition(function (position) {
alert("i'm tracking you!");
},

function (error) {
if (error.code == error.PERMISSION_DENIED){
alert("you denied me :-(");
}
});

</script>


How can i call that function only once?

Joe Joe
Answer

Just keep track of whether the watchPosition function has fired your function or not:

<script>
var firedAlready = false;

navigator.geolocation.watchPosition(function (position) {
   if(!firedAlready) {
      alert("i'm tracking you!");
      firedAlready = true;
   }
},

function (error) {
   if (error.code == error.PERMISSION_DENIED){
      alert("you denied me :-(");
   }
});

</script>