若直接調用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
})