admin管理员组

文章数量:1616032

获取用户位置,并进行个性化推荐,是一个位置应用非常重要的功能,也是目前 LBS 应用的基石。如果没有用户的位置,例如百度地图等应用就不能进行周边搜索,更不用说要持续跟踪用户位置的导航功能。

目前使用浏览器获得设备地理位置,有两种方法:第一种是使用 JavaScript Geolocation API 直接编程获取;第二种是首先获取设备的 IP 地址,然后通过查询相应的 IP 与地理位置的数据库,得到用户的地理位置。

下面,我们来分别介绍这两种方法。

1、 JavaScript Geolocation API 直接获取用户位置

目前 JavaScript 原生的 API 能直接通过浏览器获取用户地理位置,但必须得到用户许可。w3c 规定了 Geolocation API Specification(目前只是草案),在 这里 可以看到相应的规范详细内容。

关于定位方式,规范中描述如下:

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.

规范中说,API 本身并不知道位置信息的来源,可能的来源包含 GPS,IP 地址,RFID,WiFi 和 蓝牙 MAC地址,或者 GSM/CDMA cell ID ,或者用户的输入,且不能保证 API 会返回设备的真实地理位置。真实情况可能与浏览器特定的实现有关。

这个规范主要介绍了一些相关的接口和对象,下面就来看看都有那些内容。

1.1 Geolocation 接口

规范指定 Geolocation 对象是用来通过脚本编程来获得与用户的设备关联的位置信息, 在 ECMAScript 中,Geolocation 被定义为 Navigator 对象的只读属性:

 partial interface Navigator {
   readonly attribute Geolocation geolocation;
 };

Geolocation 的方法有三个: getCurrentPosition、watchPosition 和 clearWatch,调用 getCurrentPosition 和 watchPosition 都必须得到用户的允许,才能执行后续的操作。

 interface Geolocation {
    
   void getCurrentPosition(PositionCallback successCallback,
                           optional PositionErrorCallback errorCallback,
                           optional PositionOptions options);

   long watchPosition(PositionCallback successCallback,
                      optional PositionErrorCallback errorCallback,
                      optional PositionOptions options);

   void clearWatch(long watchId);
 };

1.1.1 getCurrentPositio

本文标签: 浏览器原理