由于我們剛進入頁面的時候鳞陨,就需要獲取到對應的地理位置帚戳,所以我們需要把方法寫入app.js全局文件中棵帽,然后將其存入storage中,由于存儲的要求必須是字符串旺矾,所以我們存入的時候需要將其轉(zhuǎn)化為字符串蔑鹦,使用到的時候再將其轉(zhuǎn)換為對象。需要將其寫在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里面雕崩,使用的時候只需要調(diào)用data(_this.data.addressInfo)里面的數(shù)據(jù)即可
onLoad: function (options) {
try{
const addressInfo=JSON.parse(wx.getStorageSync('addressInfo'))
this.setData({
addressInfo:addressInfo
})
}catch(e){}
},
注意:像這樣通用的,復用的屬性或者方法融撞,都可以這樣去寫盼铁,例如openid,獲取地理位置等尝偎。