`

Firefox中的geolocation API

阅读更多
无意中看到了介绍firefox的geolocation API的文章,原文链接如下:

Using geolocation https://developer.mozilla.org/en/Using_geolocation


1. The geolocation object

GEO服务由对象geolocation提供, 它是navigator下的一个子对象。如下代码可检测browser是否支持geolocation。

if (navigator.geolocation) {
  /* geolocation is available */
} else {
  alert("I'm sorry, but geolocation services are not supported by your browser.");
}


而在firefox addon中则需用另一种方式:

var geolocation = Components.classes["@mozilla.org/geolocation;1"]
                      .getService(Components.interfaces.nsIDOMGeoGeolocation);



2. Getting the current position

使用对象方法getCurrentPosition(), 它发送一个异步请求或用position hardware来获得位置信息,当有结果被返回时将调用一个回调函数。getCurrentPosition需传一个回调函数,一个可选 的错误回调,和一个可选 的参数对象。

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



3. Watching the current position

使用getCurrentPosition()。当位置数据改变时,同样会调用回调函数。需要的参数和getCurrentPosition()相同。

clearWatch()用于停止监视位置信息。

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



var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, {enableHighAccuracy:true, maximumAge:30000, timeout:27000});


一个示例网站:http://www.thedotproduct.org/experiments/geo/
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics