微信小程序--获取位置定位

2019-10-28  本文已影响0人  七號7777

手动调起地图定位,去选择定位
参考文档:https://www.cnblogs.com/lhj-blog/p/11163872.html

<span @click="getLocation">重新定位</span>
  methods: {
    getLocation: function() {
      let _this = this;
      wx.getSetting({
        success(res) {
          // 判断定位的授权
          if (!res.authSetting["scope.userLocation"]) {
            wx.authorize({
              scope: "scope.userLocation",
              success() {
                _this.chooseLocation();
              },
              fail(errMsg) {
                wx.showToast({ title: JSON.stringify(errMsg), icon: "none" });
              }
            });
          } else {
            _this.chooseLocation();
          }
        }
      });
    },
    chooseLocation: function() {
      let _this = this;
      wx.chooseLocation({
        success(e) {
          _this.setData({
            map: e.longitude + "," + e.latitude,
            addr: e.address
          });
        },
        fail(e) {
          wx.showToast({
            title: e.errMsg,
            icon: "none"
          });
        }
      });
    }
  },

ios手机小程序调用wx.chooseLocation接口的时候,获取权限的时候报authorize:fail:require permission desc这样子的错误,这是由于苹果的安全机制导致需要再app.json加上

"permission": {
    "scope.userLocation": {
      "desc": "您的位置信息将用于添加收货地址"
    }
 }

如果用户授权的时候点击拒绝,小程序则默认拒绝状态,第二次点击的时候就调用不到地图定位,则需要用户手动打开定位功能

<button open-type='openSetting' @opensetting="openSetting">打开定位</button>
openSetting(e) {//跳转授权设置之后的回调
  let that = this;
  if (e.mp.detail.authSetting['scope.userLocation']) { //此处同上同理
    wx.getLocation({
        type: 'wgs84',
        success(res) {
            const latitude = res.latitude
            const longitude = res.longitude
            const speed = res.speed
            const accuracy = res.accuracy
        },
        fail(errMsg) { 
            console.log(errMsg)
        }
     })
  }
},
image.png
上一篇 下一篇

猜你喜欢

热点阅读