vue 使用定位获取经伟度

一、第一种方法使用百度定位

  1.在public处放入

 <script type="text/javascript"src="https://api.map.baidu.com/api?v=3.0&type=webgl&ak=您的密钥"></script>

  密钥生成方法网上有许多

  2.在方法里使用

复制代码
       let that = this;
      var geolocation = new BMapGL.Geolocation();
      // 开启SDK辅助定位
      geolocation.enableSDKLocation();
      geolocation.getCurrentPosition(function(res) {
        console.log(res, "获取定位");
       if (res.accuracy == null) {
            that.load = false;            
          console.log("定位失败,请开启定位!");
            //用户拒绝地理位置授权
            return;
          }
      }); 
复制代码

 

  这样就可以得到定位了

二、使用h5的定位

  1.在方法里使用

复制代码
  let that = this;
      var location_lon = "";
      var location_lat = ""; // 经度,纬度
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          location_lon = position.coords.longitude;
          location_lat = position.coords.latitude;
          console.log(location_lon, location_lat, "获取定位");
        });
      } else {
        alert("您的设备不支持定位功能");
      }
复制代码

   这样就可以得到定位了

 

 

其它:定位不准的问题

我们可以先使用h5的定位来获取经纬度,然后通过百度来进行经纬度转换

1,查看百度经纬度转换api文档

  https://lbsyun.baidu.com/index.php?title=webapi/guide/changeposition

  

 

 

  2,这就可以知道通过请求百度api地址可以进行转换(注:如使用其它请求方式可能出现跨域问题)

  贴入代码

  此处,先要下载 npm i jsonp --save-dev 然后在页面中引用import jsonp from 'jsonp'

复制代码
 getLocation() {
      //方法二 H5 获取当前地理位置得到经纬度
      let that = this;
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          this.showLocation,
          this.locationError
        );
      } else {
        alert("您的设备不支持定位功能");
      }
    },
    showLocation(position) {
      var x = position.coords.longitude;
      var y = position.coords.latitude;
      console.log(x, y, "h5定位");
      //coords:需转换的源坐标,多组坐标以“;”分隔
(经度,纬度)
     //from :源坐标类型
      //to:目标坐标类型
jsonp( `https:
//api.map.baidu.com/geoconv/v1/?coords=${x},${y}&from=1&to=5&ak=你的密钥`, null, (err, data) => { if (err) { console.error(err.message); } else { console.log(data); } } ); }, locationError(error) { switch (error.code) { case error.PERMISSION_DENIED: alert("用户拒绝地理定位请求。"); break; case error.POSITION_UNAVAILABLE: alert("位置信息不可用。"); break; case error.TIMEOUT: alert("获取用户位置的请求超时。"); break; case error.UNKNOWN_ERROR: alert("发生未知错误。"); break; } },
复制代码

我们使用定位后需要把页面放在服务器上也就是hhtps域名上才能定位

posted @   light丶  阅读(4123)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示