How to enable GPS or show location service popup using javascipt?

2.4k Views Asked by At

I want to show an enable location service popup, just like Google Map shows it in the mobile web browser when GPS is off in mobile settings. I would like to use only javascript or jQuery, not android or Phonegap.

Would it even be possible with javascript or jQuery? Does anyone have some advice for me?

1

There are 1 best solutions below

1
Praveen Kumar On

Yes! It is possible with Browser's Geolocation API. Look at following example -

**Note: ** Geolocation API does not works as stackoverflow's code snippet. Try to run this example locally in your machine.

function geoFindMe() {

  const status = document.querySelector('#status');
  const mapLink = document.querySelector('#map-link');

  mapLink.href = '';
  mapLink.textContent = '';

  function success(position) {
    const latitude  = position.coords.latitude;
    const longitude = position.coords.longitude;

    status.textContent = '';
    mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
    mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
  }

  function error() {
    status.textContent = 'Unable to retrieve your location';
  }

  if(!navigator.geolocation) {
    status.textContent = 'Geolocation is not supported by your browser';
  } else {
    status.textContent = 'Locating…';
    navigator.geolocation.getCurrentPosition(success, error);
  }

}

document.querySelector('#find-me').addEventListener('click', geoFindMe);
<button id = "find-me">Show my location</button><br/>
<p id = "status"></p>
<a id = "map-link" target="_blank"></a>

Learn more about Geolocation API