How do I ask permission from the user, to get his location? showing an Alert with the options allow or not allow.

Asked

Viewed 1,157 times

3

How do I ask permission from the user, to get his location? showing an Alert with the options allow or not allow.

1 answer

1

It is possible by Geolocation API of the browsers, such that is accessible in the object navigator.geolocation.

Example of the MDN:

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);
}
  • Still N eh isso. , I want to be able to make the user to allow the location within my application. , I show a popup or a btn msm... And the user clicking allowing and connecting the browser location and such'z

Browser other questions tagged

You are not signed in. Login or sign up in order to post.