使用geolocation

The geolocation object

geolocation API建立在navigator.geolocation 上。

如果对象存在,才可以使用定位服务。

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

Note: 在Firefox24以及更加老的版本中,"geolocation" in navigator 总是返回true不管是否可以使用定位服务。在firefox25以后修复了这个问题。

Getting the current position

使用getCurrentPositin()来获取当前的地理位置。

这是一个监听地理位置的异步请求,当定位被授权,进行第一个回调函数。你可以设置第二个参数作为错误函数回调。你可以设置一个最大访问定位的时间作为第三个请求。

Note: 默认的,getCurrentPosition()会尽快的返回位置,所以常常以较低的精确度。有GPS的设备常常会花费更多的时间来返回较高精确度的地理位置,所以,在这些设备上使用getCurrentPosition()时返回的是根据IP亦或WIFI定位的信息。

navigator.geolocation.getCurrentPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});

当定位成功的时候将会执行do_something函数

Watching the current position

如果位置信息改变(设备的移动亦或提升地理位置的准确度),你可以设置一个调用更新的位置信息的函数。

这个函数就是watchPosition(),和getCurrentPosition()函数的输入参数一样。

回调函数将会调用多次,允许当你移动时更新你的位置,或者提高位置的精确度。

错误的回调函数,就像getCurrentPosition()里面的一样,可以被调用多次。

注意:你不能不初始化getCurrentPosition()函数就使用watchPosition().

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

watchPosition()方法将会返回一个ID,你可以使用它作为已经请求的位置监听的标识符。

你可以随后使用clearWatch()方法停止监听。

navigator.geolocation.clearWatch(watchID);

Fine tuning response

getCurrentPosiitin()和watchPosition()函数都接受一个成功回调函数,一个可选的错误回调函数,一个可选的Positionoptions 对象。

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

使用position对象中的coords属性返回用户当前位置信息。

position.coords返回了一个coordinates对象,coordinates对象定义了当前位置信息。只读。

position.timestamp返回了一个domtimestamp,定义了多少毫秒之后重新获取位置信息。

 

coordinate对象的信息:

Coordinate.latitude:返回double数据,位置的纬度

Coordinate.longtitude:返回double数据,位置经度

Coordinate.altitude:返回相对于sea level 而言的海拔高度。

Coordinate.accuracy:返回double数据,以米为单位返回了经度和纬度的准确度。

Coordinate.altitudeAccuracy:同上,返回的是海拔高度的准确性。

Coordinate.heading:返回double数据,代表了设备当前的位置。0代表了正北。顺时针方向表示和正北位置的偏差(意味着正东是90度,正西是270度)。如果速度是0,那么heaing是NaN。如果设备不能提供heading信息,那么这个值是null、

Coordinate.speed:返回double数据,岱庙了每秒中的速度,这个值可以是null。

Handling errors

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

Geolocation Live Example

HTML Content

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

JavaScript Content

 1 function geoFindMe() {
 2   var output = document.getElementById("out");
 3 
 4   if (!navigator.geolocation){
 5     output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
 6     return;
 7   }
 8 
 9   function success(position) {
10     var latitude  = position.coords.latitude;
11     var longitude = position.coords.longitude;
12 
13     output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
14 
15     var img = new Image();
16     img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
17 
18     output.appendChild(img);
19   };
20 
21   function error() {
22     output.innerHTML = "Unable to retrieve your location";
23   };
24 
25   output.innerHTML = "<p>Locating…</p>";
26 
27   navigator.geolocation.getCurrentPosition(success, error);
28 }
View Code

Prompting for permission

任何附加托管在addons.mozilla.org获取地理位置的设备必须显示的同意。就像chrom上调用地理位置时候会

下面的函数将会请求同意,就像在web页面上弹出的请求promote框一样。

当同意地理位置的时候,用户的回应将会被当做pref参数传递。函数还提供了一个callback参数作为回调,此回调包含了用户选择的布尔值,当布尔值true(也就是用户同意)时,设备将会获取地理数据信息。

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

浏览器兼容性


FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support 5.0 3.5 (1.9.1)[1] 9 10.60
No support 15.0
16.0
5
Secure origins only 50.0        

[1] Firefox包括了支持基于你的wifi使用Google Location 服务来获取你的位置信息。在Firefox和Google连接时候,传递数据包括你WIFI获取点信息,一个access 令牌(类似于两个星期的cookie),和用户ip。

Firefox 3.6 (Gecko 1.9.2)加入了Linux系统中对于GPSD的定位支持。

 

posted @ 2016-04-27 13:40  RachelChen  阅读(572)  评论(0编辑  收藏  举报