若直接调用wx.getLocation获取定位,当第一次拒绝或各种原因造成的失败,下一次无法调用,本文可解决此问题
1.app.json添加
"permission": { "scope.userLocation": { "desc": "地图选点需获取您的实时位置" } }
2.在根目录建utils/util.js
const app = getApp() import Toast from '@vant/weapp/toast/toast'; var getLocation = function (that) { wx.getLocation({ type: 'gcj02', success: function (res) { // 经纬度 var latitude = res.latitude var longitude = res.longitude wx.chooseLocation({ success: function (res) { console.log(res.name); that.setData({ location: res.name, locationShow:false }) }, }) }, fail: function () { Toast.fail("授权失败"); } }) } module.exports = { getLocation }
3.页面调用
import { getLocation } from '../../utils/util.js'
//地图选点 chooseLocation(){ //选择地址 wx.getSetting({ success: (res) => { var that = this; if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化进入该页面,且未授权 wx.showModal({ title: '是否授权当前位置', content: '需要获取您的地理位置,请确认授权,否则无法获取您所需数据', success: function (res) { if (res.cancel) { Toast.fail("授权失败"); } else if (res.confirm) { wx.openSetting({ success: function (dataAu) { if (dataAu.authSetting["scope.userLocation"] == true) { wx.showToast({ title: '授权成功', icon: 'success', duration: 1000 }) getLocation(that); } else { Toast.fail("授权失败"); } } }) } } }) } else if (res.authSetting['scope.userLocation'] == undefined) {//初始化进入 getLocation(that); } else { //授权后默认加载 getLocation(that); } } }) },
注:
1.若只需要获取该人定位,无需调用wx.chooseLocation
2.我用的vant weapp,提示可用微信小程序原生的组件
wx.showToast({
title: `经:${longitude} 纬:${latitude}`,
icon: 'none',
duration: 1000
})
来源:https://www.cnblogs.com/miaSlady/p/12566633.html