HTML5 Geolocation(地理定位)

一、背景

  • 在HTML规范中,增加了获取用户地理信息的API,这样使得可以基于用户位置开发互联网应用,即基于位置服务
  • 鉴于该特性可能侵犯用户的隐私,除非用户同意,否则用户位置信息是不可用的。
  • Internet Explorer 9+, Firefox, Chrome, Safari 和 Opera 支持Geolocation(地理定位).
  • Geolocation(地理定位)对于拥有 GPS 的设备,地理定位更加精确。

二、获取当前地信息

navigator.geolocation.getCurrentPosition(successCallback,errorCallback)

三、重复获取当前地理信息

navigator.geolocation.watchPosition(successCallback,errorCallback)

四、使用

①当获取地理信息成功后,会调用successCallback,并返回一个包含位置信息的对象position。

  • position.coords.latitude 纬度
  • position.coords.longitude 经度
  • position.coords.accuracy  精度
  • position.coords.altitude   海拔高度

②当获取地理信息失败后,会调用errorCallback,返回错误信息error

<script>
        if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(function(position){
                // 获取地理位置成功
                console.log(position.coords.latitude);//纬度
                console.log(position.coords.longitude);//经度
                console.log(position.coords.accuracy);//精度
                console.log(position.coords.altitude);//海拔高度
            },function(positionError){
                // 取地理位置失败
                console.log(positionError);//错误信息
                // 因为是从谷歌返回的数据,国家政策的原因,无法获取(需要*)
                // Network location provider at 'https://www.googleapis.com/' : No response received
            })
        }
    </script>

③在实际开发中,通过调用第三方API(如百度地图)来实现地理位置定位信息,这些API都是基于用户当前位置(经纬度)当做参数传递,就可以实现相应的功能

比如:百度地图开放平台