设为首页收藏本站

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 270|回复: 3

Web API - Using geolocation

[复制链接]
发表于 2014-3-3 11:49:19 | 显示全部楼层 |阅读模式
本帖最后由 demo 于 2014-3-4 04:04 编辑

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 objectThe 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:
  1. if ("geolocation" in navigator) {
  2.   /* geolocation is available */
  3. } else {
  4.   /* geolocation IS NOT available */
  5. }
复制代码

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

  1. navigator.geolocation.getCurrentPosition(function(position) {
  2.   do_something(position.coords.latitude, position.coords.longitude);
  3. });
复制代码

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

  1. var watchID = navigator.geolocation.watchPosition(function(position) {
  2.   do_something(position.coords.latitude, position.coords.longitude);
  3. });
复制代码

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.
  1. navigator.geolocation.clearWatch(watchID);
复制代码


Fine tuning response

Both getCurrentPosition() and watchPosition() accept a success callback, an optional error callback, and an optional PositionOptions object.
A call to watchPosition could look like:
  1. function geo_success(position) {
  2.   do_something(position.coords.latitude, position.coords.longitude);
  3. }

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

  7. var geo_options = {
  8.   enableHighAccuracy: true,
  9.   maximumAge        : 30000,
  10.   timeout           : 27000
  11. };

  12. var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
复制代码
[url=]A demo of watchPosition in use:[/url]http://www.thedotproduct.org/experiments/geo/

 楼主| 发表于 2014-3-3 11:50:25 | 显示全部楼层
本帖最后由 demo 于 2014-3-4 06:38 编辑

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

Handling errors
The error callback function, if provided when calling getCurrentPosition() or watchPosition(), expects a PositionError object as its first parameter.
  1. function errorCallback(error) {
  2.   alert('ERROR(' + error.code + '): ' + error.message);
  3. };
复制代码

Geolocation Live ExampleHTML Content
  1. <p><button onclick="geoFindMe()">Show my location</button></p>
  2. <div id="out"></div>
复制代码

JavaScript Content
  1. function geoFindMe() {
  2.   var output = document.getElementById("out");

  3.   if (!navigator.geolocation){
  4.     output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
  5.     return;
  6.   }

  7.   function success(position) {
  8.     var latitude  = position.coords.latitude;
  9.     var longitude = position.coords.longitude;

  10.     output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';

  11.     var img = new Image();
  12.     img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";

  13.     output.appendChild(img);
  14.   };

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

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

  19.   navigator.geolocation.getCurrentPosition(success, error);
  20. }
复制代码

Live Result


 楼主| 发表于 2014-3-3 11:52:29 | 显示全部楼层
本帖最后由 demo 于 2014-3-4 06:40 编辑

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.

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

  4.     if (branch.getPrefType(pref) === branch.PREF_STRING) {
  5.         switch (branch.getCharPref(pref)) {
  6.         case "always":
  7.             return callback(true);
  8.         case "never":
  9.             return callback(false);
  10.         }
  11.     }

  12.     let done = false;

  13.     function remember(value, result) {
  14.         return function() {
  15.             done = true;
  16.             branch.setCharPref(pref, value);
  17.             callback(result);
  18.         }
  19.     }

  20.     let self = window.PopupNotifications.show(
  21.         window.gBrowser.selectedBrowser,
  22.         "geolocation",
  23.         message,
  24.         "geo-notification-icon",
  25.         {
  26.             label: "Share Location",
  27.             accessKey: "S",
  28.             callback: function(notification) {
  29.                 done = true;
  30.                 callback(true);
  31.             }
  32.         }, [
  33.             {
  34.                 label: "Always Share",
  35.                 accessKey: "A",
  36.                 callback: remember("always", true)
  37.             },
  38.             {
  39.                 label: "Never Share",
  40.                 accessKey: "N",
  41.                 callback: remember("never", false)
  42.             }
  43.         ], {
  44.             eventCallback: function(event) {
  45.                 if (event === "dismissed") {
  46.                     if (!done) callback(false);
  47.                     done = true;
  48.                     window.PopupNotifications.remove(self);
  49.                 }
  50.             },
  51.             persistWhileVisible: true
  52.         });
  53. }

  54. prompt(window,
  55.        "extensions.foo-addon.allowGeolocation",
  56.        "Foo Add-on wants to know your location.",
  57.        function callback(allowed) { alert(allowed); });
复制代码


 楼主| 发表于 2014-3-3 11:54:21 | 显示全部楼层
本帖最后由 demo 于 2014-3-4 06:48 编辑

Browser compatibility

  • Desktop

      
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support53.5(1.9.1)9 10.60
Removed in 15.0
Reintroduced in 16.0
5


  • Mobile
      
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1114.0 (4)1010.603.2


Gecko notes

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

    navigator.geolocation
    Geolocation API on w3.org
    Demos about the Geolocation API
    Who moved my geolocation?(Hacks blog)
您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )  

GMT-8, 2025-8-25 20:58 , Processed in 0.017440 second(s), 17 queries .

Supported by Best Deal Online X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表