javascript – How do I ask the user's permission to get his location? showing an alert with the options to allow or not to allow.

Question:

How do I ask the user's permission to get his location? showing an alert with the options to allow or not to allow.

Answer:

It is possible via the browsers geoLocation API , such that it is accessible in the navigator.geolocation object.

MDN example:

HTML

<p><button onclick="geoFindMe()">Exibir minha localização</button></p>
<div id="out"></div>

JS

function geoFindMe() {
  var output = document.getElementById("out");

  if (!navigator.geolocation){
    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
    return;
  }

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

    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';

    var img = new Image();
    img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";

    output.appendChild(img);
  }

  function error() {
    output.innerHTML = "Unable to retrieve your location";
  }

  output.innerHTML = "<p>Locating…</p>";

  navigator.geolocation.getCurrentPosition(success, error);
}
Scroll to Top
AllEscort