微信小程序獲取地理位置及經緯度授權代碼實例
更新時間:2019年09月18日 15:05:16 作者:fanmengfei
這篇文章主要介紹了微信小程序獲取地理位置及經緯度授權代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
這篇文章主要介紹了微信小程序獲取地理位置及經緯度授權代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
微信小程序獲取地理位置授權,首先需要在app.json中添加配置:
"permission": {
"scope.userLocation": {
"desc": "請確認授權"
}
}
獲取經緯度:如果手機未開啟位置信息,那么授權成功后在wx.getLocation()方法中也會一直失敗,所以需要在fail方法中提示用戶開啟手機位置信息
getUserLocation: function () {
let vm = this
wx.getSetting({
success: (res) => {
// res.authSetting['scope.userLocation'] == undefined 表示 初始化進入該頁面
// res.authSetting['scope.userLocation'] == false 表示 非初始化進入該頁面,且未授權
// res.authSetting['scope.userLocation'] == true 表示 地理位置授權
// 拒絕授權后再次進入重新授權
if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
// console.log('authSetting:status:拒絕授權后再次進入重新授權', res.authSetting['scope.userLocation'])
wx.showModal({
title: '',
content: '【泰福利Lite】需要獲取你的地理位置,請確認授權',
success: function (res) {
if (res.cancel) {
wx.showToast({
title: '拒絕授權',
icon: 'none'
})
setTimeout(() => {
wx.navigateBack()
}, 1500)
} else if (res.confirm) {
wx.openSetting({
success: function (dataAu) {
// console.log('dataAu:success', dataAu)
if (dataAu.authSetting["scope.userLocation"] == true) {
//再次授權,調用wx.getLocation的API
vm.getLocation(dataAu)
} else {
wx.showToast({
title: '授權失敗',
icon: 'none'
})
setTimeout(() => {
wx.navigateBack()
}, 1500)
}
}
})
}
}
})
}
// 初始化進入,未授權
else if (res.authSetting['scope.userLocation'] == undefined) {
// console.log('authSetting:status:初始化進入,未授權', res.authSetting['scope.userLocation'])
//調用wx.getLocation的API
vm.getLocation(res)
}
// 已授權
else if (res.authSetting['scope.userLocation']) {
// console.log('authSetting:status:已授權', res.authSetting['scope.userLocation'])
//調用wx.getLocation的API
vm.getLocation(res)
}
}
})
},
// 微信獲得經緯度
getLocation: function (userLocation) {
let vm = this
wx.getLocation({
type: "wgs84",
success: function (res) {
// console.log('getLocation:success', res)
var latitude = res.latitude
var longitude = res.longitude
vm.getDaiShu(latitude, longitude)
},
fail: function (res) {
// console.log('getLocation:fail', res)
if (res.errMsg === 'getLocation:fail:auth denied') {
wx.showToast({
title: '拒絕授權',
icon: 'none'
})
setTimeout(() => {
wx.navigateBack()
}, 1500)
return
}
if (!userLocation || !userLocation.authSetting['scope.userLocation']) {
vm.getUserLocation()
} else if (userLocation.authSetting['scope.userLocation']) {
wx.showModal({
title: '',
content: '請在系統設置中打開定位服務',
showCancel: false,
success: result => {
if (result.confirm) {
wx.navigateBack()
}
}
})
} else {
wx.showToast({
title: '授權失敗',
icon: 'none'
})
setTimeout(() => {
wx.navigateBack()
}, 1500)
}
}
})
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
用JavaScript實現PHP的urlencode與urldecode函數
這篇文章主要介紹了用JavaScript實現PHP的urlencode與urldecode函數,很多情況下我們用了出來php urlencode出來的網址,需要的朋友可以參考下2015-08-08

