由于我们刚进入页面的时候,就需要获取到对应的地理位置,所以我们需要把方法写入app.js全局文件中,然后将其存入storage中,由于存储的要求必须是字符串,所以我们存入的时候需要将其转化为字符串,使用到的时候再将其转换为对象。需要将其写在try catch里面。
utils/getLocation.js(这是封装好的)
export const getAddress = function (wx) {
return new Promise((resolve, reject) => {
let _this = this
wx.getSetting({
success: (res) => {
let authSetting = res.authSetting
if (authSetting['scope.userLocation']) {
// 已授权
console.log("已授权")
getLocation2(true)
} else {
// 未授权
console.log("未授权")
getLocation2(false)
}
}
})
function getLocation2 () {
let _this = this;
wx.getLocation({
type: 'wgs84',
success(res) {
getWechatLocationInfo(res.latitude, res.longitude);
},
fail() {
console.log("获取定位失败")
if (!userLocation) {
wx.showModal({
title: '警告',
content: '您未授权地理位置信息,将无法正常使用小程序,请打开允许授权',
success(res) {
if (res.confirm) {
_this.openSetting()
}
}
})
} else {
wx.showModal({
title: '警告',
showCancel: false,
content: '获取位置信息失败,请打开手机的定位功能!',
success() {}
});
}
}
});
}
function getWechatLocationInfo(latitude, longitude) {
let query = {
latitude: latitude,
longitude: longitude
};
wx.request({
url: `后台写好的请求接口地址`,
method: 'get',
data: query,
success: function (res) {
let data = {
...res.data.data,
address: `${res.data.data.province} ${res.data.data.city} ${res.data.data.district} ${res.data.data.street}`
}
resolve(data)
},
fail: function (err) {
reject(err)
}
})
}
})
}
app.js
import {getAddress} from './utils/getLocation'
App({
onLaunch() {
getAddress(wx).then(res => {
console.log(res);
try{
wx.setStorageSync('addressInfo',JSON.stringify(res))
}catch(e){}
})
}
})
再其他页面使用的时候,在onLoad中将其存入到data里面,使用的时候只需要调用data(_this.data.addressInfo)里面的数据即可
onLoad: function (options) {
try{
const addressInfo=JSON.parse(wx.getStorageSync('addressInfo'))
this.setData({
addressInfo:addressInfo
})
}catch(e){}
},
注意:像这样通用的,复用的属性或者方法,都可以这样去写,例如openid,获取地理位置等。