Web 端获取地理位置

HTML5 Geolocation API

if (navigator.geolocation) {
   navigator.geolocation.getCurrentPosition(function(position) {
        var latitude  = position.coords.latitude;
        var longitude = position.coords.longitude;
        alert('h5定位成功: latitude:' + latitude + "  longitude:" + longitude);
      }, function(error) {
        switch(error.code){
          case error.TIMEOUT:
             alert('超时'); break;
          case error.PERMISSION_DENIED:
             alert('用户拒绝提供地理位置');break;
          case error.POSITION_UNAVAILABLE:
             alert('地理位置不可用');break;
          default:break;
         }
     })
}

备注:

1、Chrome浏览器从50版本开始,http协议的网址是不能用了。控制台会有这样的提示:
       getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://goo.gl/rStTGz for more details.
       各类浏览器支持性不好
   2、移动端支持性不是特别好,经测试:大部分安卓手机不支持,ios的支持度还可以

百度地图web ip定位(用空试下腾讯地图)

文档位置:
  百度地图开放平台---Web服务API---普通IP定位API,链接:http://lbsyun.baidu.com/index.php?title=webapi/ip-api
  注意事项:未认证的开发者账号每天配额查询IP数量为10W次,并发6k每分钟。

第一步:申请密钥(ak),作为访问服务的依据

申请地址:http://lbsyun.baidu.com/apiconsole/key?application=key

  提交后可获取相应的 ak 秘钥

第二步:引入js,上代码

  Js:

<script type="text/javascript" src="//api.map.baidu.com/api?v=2.0&ak=你的密钥"></script>
function getCity() {
    var geoc = new BMap.Geocoder();
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            var pt = r.point;
            geoc.getLocation(pt, function (rs) {
              //addComp.province city district street streetNumber
              var addComp = rs.addressComponents; 
            });
        } else {
            console.log('failed' + this.getStatus());
        }   
    }, { enableHighAccuracy: true });
}

​

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章