300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 微信小程序获取当前位置并根据经纬度跳转地图导航

微信小程序获取当前位置并根据经纬度跳转地图导航

时间:2022-09-30 06:42:08

相关推荐

微信小程序获取当前位置并根据经纬度跳转地图导航

方式一

<view><map id="map" longitude="{{longitude}}" latitude="{{latitude}}" scale="14" markers="{{markers}}" show-location></map></view>

data = {//当前定位位置latitude: '',longitude: '',}methods = {//这个函数是一开始点击事件触发的:async authorization() {let self = thistry {await this.getWxLocation() //等待} catch (error) {wx.showModal({title: '温馨提示',content:'获取权限失败,需要获取您的地理位置才能为您提供更好的服务!是否授权获取地理位置?',success: function(res) {self.toSetting()},fail: function(res) {},})return}},}getWxLocation() {wx.showLoading({title: '定位中...',mask: true,})return new Promise((resolve, reject) => {let _locationChangeFn = (res) => {console.log('location change', res)// Storage.set('userLocation', res)this.latitude = res.latitudethis.longitude = res.longitudewx.stopLocationUpdate(_locationChangeFn); // 关闭监听 不关闭监听的话,有时获取位置时会非常慢wx.hideLoading()wx.offLocationChange(_locationChangeFn)}wx.startLocationUpdate({success: (res) => {console.log(res, 'startLocationUpdate')wx.onLocationChange(_locationChangeFn)resolve()},fail: (err) => {console.log('获取当前位置失败', err)wx.hideLoading()reject()},})// 可以指定经纬度30.333882,120.115576wx.openLocation({latitude: Number(this.storeInfo.latitude), //要去的纬度,这里需要数字类型不然会报错longitude: Number(this.storeInfo.longitude), //要去的经度address:this.storeInfo.province +this.storeInfo.city +this.storeInfo.district +this.storeInfo.address, //要去的详细地址name: this.storeInfo.name, //要去的建筑名称})})}toSetting() {let self = thiswx.openSetting({success(res) {console.log(res)if (res.authSetting['scope.userLocation']) {// res.authSetting["scope.userLocation"]为trueb表示用户已同意获得定位信息,此时调用getlocation可以拿到信息self.authorization()}},})}

思路主要是这样的:首先事件触发authorization函数,等待getWxLocation函数里面的结果处理,看文档知道在调用onLocationChange前先调用startLocationUpdate

等待startLocationUpdate的成功回调打印一下内容,说明开启小程序进入前台时接收位置消息成功了

成功之后,在回调里面就可以调用onLocationChange去监听实时地理位置变化(注意:目前只有真机开启调试模式打印才能看到返回的坐标等参数,电脑调试暂时不行

获取之后要记得关闭实时监听wx.offLocationChange(_locationChangeFn),不然就会一直去获取坐标,可能会导致手机耗电严重。

如果是startLocationUpdate是失败回调的话:就去调用wx.openSetting申请用户的定位权限(scope.userLocation)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。