Esta tradução está incompleta. Por favor, ajude a traduzir este artigo do Inglês.

Secure context
This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

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

O objeto de geolocalização

The geolocation API is published through the navigator.geolocation object.

If the object exists, geolocation services are available. You can test for the presence of geolocation thusly:

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

Note: 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 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, 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 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 watchPosition() function, which has the same input parameters as 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 getCurrentPosition(), can be called repeatedly.

Nota: You can use watchPosition() without an initial getCurrentPosition() call.

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

The 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 clearWatch() method to stop watching the user's location.


Resposta de ajuste preciso

Both getCurrentPosition() and watchPosition() accept a success callback, an optional error callback, and an optional PositionOptions object.

A call to 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.

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

Exemplor 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>";

  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 = "" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";


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

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

  navigator.geolocation.getCurrentPosition(success, error);

Resultado Live

Aviso para permissão

Any add-on hosted on 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[";1"]

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

    let self =
            label: "Share Location",
            accessKey: "S",
            callback: function(notification) {
                done = 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;
            persistWhileVisible: true

       "Foo Add-on wants to know your location.",
       function callback(allowed) { alert(allowed); });

Compatibilidade de navegador

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Funcionalidade Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Suporte básico 5.0 (Yes) 3.5 (1.9.1)[1] 9 10.60
No support 15.0
Apenas origens seguras 50.0 No support 55 (55) No support 39 10
Funcionalidade Android Android Webview Edge Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Suporte básico ? (Yes) (Yes) 4.0 (4) 1.0.1 ? 10.60
No support 15.0
3.2 (Yes)
Apenas origens seguras ? 50.0 No support 55.0 (55)       10.1 50.0

[1] Firefox includes support for locating you based on your WiFi information using Google Location Services. In the transaction between Firefox and Google, data is exchanged including WiFi Access Point data, an access token (similar to a 2 week cookie), and the user's IP address. For more information, please check out Mozilla's Privacy Policy and Google's Privacy Policy covering how this data can be used.

[2] Because of [1], this API is unusable in China. Use Baidu's or Autonavi's API instead.

Firefox 3.6 (Gecko 1.9.2) added support for using the GPSD (GPS daemon) service for geolocation on Linux.

Consulte também

Etiquetas do documento e contribuidores

Contribuidores para esta página: mansil
Última atualização por: mansil,