微信小程序位置

wx.openLocation  获取定位打开地图,配合wx.getLocation得到的经纬度实现定位,不能单独使用

wx.chooseLocation  根据已有的经纬度打开地图

<view class="location-1" bindtap="open_location_1">
  定位
</view>
<view class="location-2"  bindtap="open_location_2">定位2</view>
 
 open_location_1(){
    console.log("我被点击了")

    wx.getSetting({
      success:res=>{
        console.log(res)
        if(!res.authSetting["scope.userLocation"]){
          // 未开启定位
          wx.showModal({
            title:'提示',
            content:'我们需要获取您的位置信息,为您提供更多的精彩内容',
            confirmText:"授权",
            cancelText:"取消",
            success:res=>{
              if(res.confirm){
                wx.openSetting({
                  success:res=>{
                    wx.getLocation({
                      type:'gcj02',
                      success:res=>{
                        console.log(res)
                        wx.openLocation({
                          latitude: res.latitude,
                          longitude:res.longitude,
                          success:res=>{
                            console.log('成功',res)
                          }
                        })
                      }
                    })
                  }
                })
              }else{
                wx.showToast({
                  title: '您拒绝了授权,请在设置中开启授权定位',
                })
              }
            }
          })
        }else{
         wx.getLocation({
            type:'gcj02',
            success:res=>{
              console.log(res)
              wx.openLocation({
                latitude: res.latitude,
                longitude:res.longitude,
                success:res=>{
                  console.log('成功',res)
                }
              })
            }
          })
        }
      }
    })
    
  },

注意使用wx.getLocation需要在app.json中加上这个属性

"permission": {
    "scope.userLocation": {
      "desc": "地图选点需获取您的实时位置"
    }
  },
 open_location_2(){
   var latitude= 31.82057
   var longitude= 117.22901

   wx.chooseLocation({
     latitude:latitude,
     longitude:longitude,
     success:res=>{
       console.log(res)
     },fail:err=>{
       if(err.errMsg=="chooseLocation:fail auth deny"){
        wx.openSetting({
         success:res=>{
           console.log(res)
           if(!res.authSetting["scope.userLocation"]){
             wx.showToast({
               title: '你拒绝了授权,请在设置中自行授权定位',
             })
           }else{
            wx.chooseLocation({
              latitude:latitude,
              longitude:longitude,
              success:res=>{
                console.log(res)
              }
            })
           }
         }
        })
       }
     }
   })
  },

猜你喜欢

转载自www.cnblogs.com/shanchui/p/13379199.html