--- title: API de Geolocalização slug: Web/API/Geolocation_API tags: - API de Geolocalização - Guía - Intermediário translation_of: Web/API/Geolocation_API original_slug: Web/API/Geolocation/Utilizacao_da_geolocalizacao ---

{{securecontext_header}}{{APIRef("Geolocation API")}}

A API de geolocalização permite que o utilizador forneça a sua localização nas aplicações da Web, se assim o desejar. Por motivos de segurança, é solicitado ao utilizador para dar permissão para informar a informação da localização.

O objeto de geolocalização

A API de Geolocation é publicada através do objeto {{domxref("navigator.geolocation")}}.

Se o objeto existir, os serviços de geolocalização estarão disponíveis. Pode testar a presença de geolocalização assim:

if ("geolocation" in navigator) {
  /* geolocation is available */
} else {
  /* geolocation IS NOT available */
}

Nota: On Firefox 24 and older versions, "geolocation" in navigator always returned true even if the API was disabled. This has been fixed with Firefox 25 to comply with the spec. ({{bug(884921)}}).

Obter a posição atual

To obtain the user's current location, you can call the {{domxref("geolocation.getCurrentPosition()","getCurrentPosition()")}} method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.

Nota: By default, {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} tries to answer as fast as possible with a low accuracy result. It is useful if you need a quick answer regardless of the accuracy. Devices with a GPS, for example, can take a minute or more to get a GPS fix, so less accurate data (IP location or wifi) may be returned to {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}.

navigator.geolocation.getCurrentPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});

The above example will cause the do_something() function to execute when the location is obtained.

Vigiar a posição atual

If the position data changes (either by device movement or if more accurate geo information arrives), you can set up a callback function that is called with that updated position information. This is done using the {{domxref("Geolocation.watchPosition()","watchPosition()")}} function, which has the same input parameters as {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}. The callback function is called multiple times, allowing the browser to either update your location as you move, or provide a more accurate location as different techniques are used to geolocate you. The error callback function, which is optional just as it is for {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}, can be called repeatedly.

Nota: pode utilizar {{domxref("Geolocation.watchPosition()","watchPosition()")}} sem uma chamada inicial {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}.

var watchID = navigator.geolocation.watchPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});

The {{domxref("Geolocation.watchPosition()","watchPosition()")}} method returns an ID number that can be used to uniquely identify the requested position watcher; you use this value in tandem with the {{domxref("Geolocation.clearWatch()","clearWatch()")}} method to stop watching the user's location.

navigator.geolocation.clearWatch(watchID);

Resposta de ajuste preciso

Both {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} and {{domxref("Geolocation.watchPosition()","watchPosition()")}} accept a success callback, an optional error callback, and an optional PositionOptions object.

{{page("/en-US/docs/DOM/navigator.geolocation.getCurrentPosition","PositionOptions")}}

A call to {{domxref("Geolocation.watchPosition()","watchPosition")}} could look like:

function geo_success(position) {
  do_something(position.coords.latitude, position.coords.longitude);
}

function geo_error() {
  alert("Sorry, no position available.");
}

var geo_options = {
  enableHighAccuracy: true,
  maximumAge        : 30000,
  timeout           : 27000
};

var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);

Descrever uma posição

The user's location is described using a Position object referencing a Coordinates object.

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Position")}}

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Coordinates")}}

Lidar com erros

The error callback function, if provided when calling getCurrentPosition() or watchPosition(), expects a PositionError object as its first parameter.

function errorCallback(error) {
  alert('ERROR(' + error.code + '): ' + error.message);
};

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","PositionError")}}

Exemplo de Geolocalização Live

Conteúdo HTML

<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>

Conteúdo JavaScript

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);
}

Resultado Live

{{EmbedLiveSample('Geolocation_Live_Example', 350, 410)}}

Aviso para permissão

Any add-on hosted on addons.mozilla.org which makes use of geolocation data must explicitly request permission before doing so. The following function will request permission in a manner similar to the automatic prompt displayed for web pages. The user's response will be saved in the preference specified by the pref parameter, if applicable. The function provided in the callback parameter will be called with a boolean value indicating the user's response. If true, the add-on may access geolocation data.

function prompt(window, pref, message, callback) {
    let branch = Components.classes["@mozilla.org/preferences-service;1"]
                           .getService(Components.interfaces.nsIPrefBranch);

    if (branch.getPrefType(pref) === branch.PREF_STRING) {
        switch (branch.getCharPref(pref)) {
        case "always":
            return callback(true);
        case "never":
            return callback(false);
        }
    }

    let done = false;

    function remember(value, result) {
        return function() {
            done = true;
            branch.setCharPref(pref, value);
            callback(result);
        }
    }

    let self = window.PopupNotifications.show(
        window.gBrowser.selectedBrowser,
        "geolocation",
        message,
        "geo-notification-icon",
        {
            label: "Share Location",
            accessKey: "S",
            callback: function(notification) {
                done = true;
                callback(true);
            }
        }, [
            {
                label: "Always Share",
                accessKey: "A",
                callback: remember("always", true)
            },
            {
                label: "Never Share",
                accessKey: "N",
                callback: remember("never", false)
            }
        ], {
            eventCallback: function(event) {
                if (event === "dismissed") {
                    if (!done) callback(false);
                    done = true;
                    window.PopupNotifications.remove(self);
                }
            },
            persistWhileVisible: true
        });
}

prompt(window,
       "extensions.foo-addon.allowGeolocation",
       "Foo Add-on wants to know your location.",
       function callback(allowed) { alert(allowed); });

Compatibilidade de navegador

{{Compat("api.Geolocation")}}

Disponibilidade

Como a localização baseada em Wi-Fi é geralmente fornecida pelo Google, a API de Geolocalização "vanilla" pode estar indisponível na China. Pode utilizar os provedores locais de terceiros, tais como  Baidu, Autonavi, ou Tencent. Estes serviços utilziam o endereço de IP do utilizador e/ou uma aplicação local para fornecer o posicionamento melhorado.

Consulte também