0

I am trying to implement something like below.

When user comes to my page his location will be taken by clicking on button. If that location is valid based on defined location then further process will be done. If invalid it just shows a "try again" message and not proceed further.

I tried with containLocation() method but it did not work for me

Below is the code I have implemented (I just take location of user).

What to do after this?

var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}
<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

this is picture representation what I want to do if my English is bad image

  • What is the actual issue here? That the browser does not allow the location or you do not know what to do with it afterwards? – mplungjan Apr 04 '20 at 07:02

2 Answers2

0

Here is a version that will give more information - for example it won't run in a stacksnippet

let x;
const showPosition = position => {
  x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
};
const posError =  error => console.log('Sorry cannot return location',error);
    

window.addEventListener("load", function() {
  x = document.getElementById("demo");
  document.getElementById("locBut").addEventListener("click", function() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition, posError);
    } else {
      x.innerHTML = "Geolocation is not supported by this browser.";
    }
  });
});
<p>Click the button to get your coordinates.</p>

<button type="button" id="locBut">Try It</button>

<p id="demo"></p>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

I ran your conde in firefox asked me:

firefox asked

See here: https://support.mozilla.org/en-US/kb/does-firefox-share-my-location-websites?redirectlocale=en-US&redirectslug=does-firefox-share-my-location-web-sites

So the answer is :

Now, what should you do with the longitude and latitude? You can use a geocoding service like google maps https://developers.google.com/maps/documentation/geocoding/intro

  • I believe the answer is more like https://stackoverflow.com/questions/13840516/how-to-find-my-distance-to-a-known-location-in-javascript – mplungjan Apr 04 '20 at 07:22