From 41c76addc97200aa71105773397aa4edd2af6b4c Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:44:35 +0100 Subject: unslug ar: move --- .../api/geolocation/using_geolocation/index.html | 294 --------------------- .../using_the_geolocation_api/index.html | 166 ------------ 2 files changed, 460 deletions(-) delete mode 100644 files/ar/web/api/geolocation/using_geolocation/index.html delete mode 100644 files/ar/web/api/geolocation/using_geolocation/using_the_geolocation_api/index.html (limited to 'files/ar/web/api/geolocation') diff --git a/files/ar/web/api/geolocation/using_geolocation/index.html b/files/ar/web/api/geolocation/using_geolocation/index.html deleted file mode 100644 index a27275b2b5..0000000000 --- a/files/ar/web/api/geolocation/using_geolocation/index.html +++ /dev/null @@ -1,294 +0,0 @@ ---- -title: Using geolocation -slug: Web/API/Geolocation/Using_geolocation -translation_of: Web/API/Geolocation_API ---- -

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 object

- -

The geolocation API is published through the {{domxref("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)}}).

-
- -

Getting the current position

- -

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.

- -
-

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

- -

Watching the current position

- -

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.

- -
-

Note: You can use {{domxref("Geolocation.watchPosition()","watchPosition()")}} without an initial {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} call.

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

Fine tuning response

- -

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

A demo of watchPosition in use: http://www.thedotproduct.org/experiments/geo/
- 

- -

Describing a position

- -

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

- -

Handling errors

- -

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

- -

Geolocation Live Example

- - - -

HTML Content

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

JavaScript Content

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

Live Result

- -

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

- -

Prompting for permission

- -

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

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{CompatGeckoDesktop("1.9.1")}}[1]910.60
- {{CompatNo}} 15.0
- 16.0
5
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("4")}}1.0.1{{CompatUnknown}}10.60
- {{CompatNo}} 15.0
- 16.0
{{CompatUnknown}}
-
- -

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

- -

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

- -

See also

- - diff --git a/files/ar/web/api/geolocation/using_geolocation/using_the_geolocation_api/index.html b/files/ar/web/api/geolocation/using_geolocation/using_the_geolocation_api/index.html deleted file mode 100644 index d696d6c9f2..0000000000 --- a/files/ar/web/api/geolocation/using_geolocation/using_the_geolocation_api/index.html +++ /dev/null @@ -1,166 +0,0 @@ ---- -title: Using the Geolocation API -slug: Web/API/Geolocation/Using_geolocation/Using_the_Geolocation_API -translation_of: Web/API/Geolocation_API/Using_the_Geolocation_API ---- -
{{securecontext_header}}{{DefaultAPISidebar("Geolocation API")}}
- -

The Geolocation API is used to retrieve the user's location, so that it can for example be used to display their position using a mapping API. This article explains the basics of how to use it.

- -

The geolocation object

- -

The Geolocation API is available through the {{domxref("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 */
-}
-
- -

Getting the current position

- -

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.

- -
-

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

- -

Watching the current position

- -

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.

- -
-

Note: You can use {{domxref("Geolocation.watchPosition()","watchPosition()")}} without an initial {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} call.

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

Fine tuning the response

- -

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

- -

This object allows you to specify whether to enable high accuracy, a maximum age for the returned position value (up until this age it will be cached and reused if the same position is requested again; after this the browser will request fresh position data), and a timeout value that dictates how long the browser should attempt to get the position data for, before it times out.

- -

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

Describing a position

- -

The user's location is described using a {{domxref("GeolocationPosition")}} object instance, which itself contains a {{domxref("GeolocationCoordinates")}} object instance.

- -

The GeolocationPosition instance contains only two things, a coords property that contains the GeolocationCoordinates instance, and a timestamp property that contains a {{domxref("DOMTimeStamp")}} instance representing the time at which the position data was retrieved.

- -

The GeolocationCoordinates instance contains a number of properties, but the two you'll use most commonly are latitude and longitude, which are what you need to draw your position on a map. Hence many Geolocation success callbacks look fairly simple:

- -
function success(position) {
-  const latitude  = position.coords.latitude;
-  const longitude = position.coords.longitude;
-
-  // Do something with your latitude and longitude
-}
- -

You can however get a number of other bits of information from a GeolocationCoordinates object, including altitude, speed, what direction the device is facing, and an accuracy measure of the altitude, longitude, and latitude data.

- -

Handling errors

- -

The error callback function, if provided when calling getCurrentPosition() or watchPosition(), expects a GeolocationPositionError object instance as its first parameter. This object type contains two properties, a code indicating what type of error has been returned, and a human-readable message that describes what the error code means.

- -

You could use it like so:

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

Examples

- -

In the following example the Geolocation API is used to retrieve the user's latitude and longitude. If sucessful, the available hyperlink is populated with an openstreetmap.org URL that will show their location.

- - - -

HTML Content

- -
<button id = "find-me">Show my location</button><br/>
-<p id = "status"></p>
-<a id = "map-link" target="_blank"></a>
-
- -

JavaScript Content

- -
function geoFindMe() {
-
-  const status = document.querySelector('#status');
-  const mapLink = document.querySelector('#map-link');
-
-  mapLink.href = '';
-  mapLink.textContent = '';
-
-  function success(position) {
-    const latitude  = position.coords.latitude;
-    const longitude = position.coords.longitude;
-
-    status.textContent = '';
-    mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
-    mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
-  }
-
-  function error() {
-    status.textContent = 'Unable to retrieve your location';
-  }
-
-  if (!navigator.geolocation) {
-    status.textContent = 'Geolocation is not supported by your browser';
-  } else {
-    status.textContent = 'Locating…';
-    navigator.geolocation.getCurrentPosition(success, error);
-  }
-
-}
-
-document.querySelector('#find-me').addEventListener('click', geoFindMe);
-
- -

Live Result

- -

{{EmbedLiveSample('Examples', 350, 150, "", "", "", "geolocation")}}

-- cgit v1.2.3-54-g00ecf