Secure context
This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.
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).
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.
Note: 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.
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.
Note: 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);
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);
The user's location is described using a Position
object referencing a Coordinates
object.
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); };
<p><button onclick="geoFindMe()">Show my location</button></p> <div id="out"></div>
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); }
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); });
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | 5 | 12 | 3.5
|
9 | 16
|
5 |
Secure context required | 50 | ? | 55 | No | 37 | Yes |
clearWatch |
5 | Yes | 3.5 | 9 | 16
|
Yes |
getCurrentPosition |
5 | Yes | 3.5 | 9 | 16
|
Yes |
watchPosition |
5 | Yes | 3.5 | 9 | 16
|
Yes |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | Yes | 12 | 4 | 15 | Yes | Yes |
Secure context required | 51
|
50 | ? | 55 | 37 | Yes | ? |
clearWatch |
Yes | Yes | Yes | 4 | 15 | Yes | Yes |
getCurrentPosition |
Yes | Yes | Yes | 4 | 15 | Yes | Yes |
watchPosition |
Yes | ? | Yes | 4 | 15 | Yes | Yes |
As WiFi-based locationing is often provided by Google, the vanilla Geolocation API may be unavailable in China. You may use local third-party providers such as Baidu, Autonavi, or Tencent. These services use the user's IP address and/or a local app to provide enhanced positioning.
navigator.geolocation
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API