HTML5-地理定位

HTML5 Geolocation(地理定位)用于定位用户的位置。

定位用户的位置

HTML5 Geolocation API 用于获得用户的地理位置。

鉴于该特性可能侵犯用户的隐私,除非用户同意,否则用户位置信息是不可用的。

浏览器支持

Internet Explorer 9、Firefox、Chrome、Safari 以及 Opera 支持地理定位。对于拥有 GPS 的设备,比如 iPhone,地理定位更加精确。

使用地理定位

HTML5中,navigator.geolocation作为定位對象,拥有三个方法:

  • getCurrentPosition: sucfunc為执行成功的回调函数,errfunc為執行失败的回调函数,options為getCurrentPosition的参数對象

  e.g.navigator.geolocation.getCurrentPosition(sucfunc, errfunc, options);

  • watchPosition: watchPosition和getCurrentPosition類似,但是只要设备位置发生变化,就会执行

  e.g.var watcherId = navigator.geolocation.watchPosition(sucfunc, errfunc, options);

  • clearWatch: clearwatch用于终止watchPosition方法

  e.g.navigator.geolocation.clearWatch(watcherId);

原理

W3C對Geolocation描述如下:

The Geolocation API defines a high-level interface to location information associated only with the device hosting the implementation, such as latitude and longitude. The API itself is agnostic of the underlying location information sources. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs, as well as user input. No guarantee is given that the API returns the device's actual location.

geolocation的位置信息来源包括GPS、IP地址、RFID、WIFI和蓝牙的MAC地址、以及GSM/CDMS的ID等等。规范中没有规定使用这些设备的先后顺序,在HTML5的实现中,移動設備如果使用GPS,則優先使用GPS定位,如果使用了WIFI,則根據WIFI熱點定位,如果使用網線接入,則使用IP來定位,這個準確點則是最低的。

使用GPS可以直接獲取到位置信息,但是對於WIFI和IP定位,瀏覽器本身并不能直接解析,它只能收集WIFI及IP信息,然後通過這些信息請求位置信息服務接口來提供,主流瀏覽器都是使用Google提供的地理位置查詢服務。以Chrome為例,會請求www.googleapi.com解析位置信息。

 

參考:

http://www.w3school.com.cn/html5/html_5_geolocation.asp

http://dev.w3.org/geo/api/spec-source.html

posted @ 2014-06-10 17:08  swzhou  阅读(519)  评论(0编辑  收藏  举报