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 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 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 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.

navigator.geolocation.clearWatch(watchID);

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

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

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung Internet
Basic supportChrome Full support 5Edge Full support 12Firefox Full support 3.5
Notes
Full support 3.5
Notes
Notes GPSD (GPS daemon) support added in Firefox 3.6. WiFi-based location is provided by Google (privacy) or a custom provider (MLS instructions).
IE Full support 9Opera Full support 16
Full support 16
No support 10.6 — 15
Safari Full support 5WebView Android Full support YesChrome Android Full support YesEdge Mobile Full support 12Firefox Android Full support 4Opera Android Full support 15Safari iOS Full support YesSamsung Internet Android Full support Yes
Secure context requiredChrome Full support 50Edge ? Firefox Full support 55IE No support NoOpera Full support 37Safari Full support YesWebView Android Full support 51
Notes
Full support 51
Notes
Notes Secure context is only required for applications targeting Android Nougat (7) and higher. See bug 603574.
Chrome Android Full support 50Edge Mobile ? Firefox Android Full support 55Opera Android Full support 37Safari iOS Full support YesSamsung Internet Android ?
clearWatchChrome Full support 5Edge Full support YesFirefox Full support 3.5IE Full support 9Opera Full support 16
Full support 16
No support 10.6 — 15
Safari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support 15Safari iOS Full support YesSamsung Internet Android Full support Yes
getCurrentPositionChrome Full support 5Edge Full support YesFirefox Full support 3.5IE Full support 9Opera Full support 16
Full support 16
No support 10.6 — 15
Safari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support 15Safari iOS Full support YesSamsung Internet Android Full support Yes
watchPositionChrome Full support 5Edge Full support YesFirefox Full support 3.5IE Full support 9Opera Full support 16
Full support 16
No support 10.6 — 15
Safari Full support YesWebView Android Full support YesChrome Android ? Edge Mobile Full support YesFirefox Android Full support 4Opera Android Full support 15Safari iOS Full support YesSamsung Internet Android Full support Yes

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
See implementation notes.
See implementation notes.

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

Etiquetas do documento e contribuidores

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