wx.getSetting({
success: (res) => {
if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
wx.showModal({
title: '请求授权当前位置',
content: '需要获取您的地理位置,请确认授权',
success: function(res) {
if (res.cancel) {
wx.showToast({
title: '拒绝授权',
icon: 'none',
duration: 1000
})
} else if (res.confirm) {
wx.openSetting({
success: function(dataAu) {
if (dataAu.authSetting["scope.userLocation"] == true) {
wx.showToast({
title: '授权成功',
icon: 'success',
duration: 1000
})
//再次授权,调用wx.getLocation的API
wx.getLocation({ // 用户同意授权地理位置
type: 'wgs84',
success: function(res) {
var locationString = res.latitude + "," + res.longitude;
wx.request({
url: 'http://apis.map.qq.com/ws/geocoder/v1/',
data: {
"key": "2IDBZ-O5OC3-WOB3U-YNDUM-WJ4J7-7PFHY",
"location": locationString
},
method: 'GET',
success: function(r) {
// 获取城市
let city = r.data.result.address_component.city
}
});
},
fail: function(err) { // 用户拒绝授权地理位置
wx.showModal({ //弹出模态框,询问
title: '是否授权当前位置',
content: '如需正常使用本程序,请按确定并在授权管理中选中“地理位置”,然后点按返回即可正常使用。',
cancelColor: '#f00',
success: function(res) {
if (res.confirm) { //同意授权
wx.openSetting({})
} else if (res.cancel) { //不同意授权,进行普通查询
}
}
})
}
})
} else {
wx.showToast({
title: '授权失败',
icon: 'none',
duration: 1000
})
}
}
})
}
}
})
} else if (res.authSetting['scope.userLocation'] == undefined) {
//调用wx.getLocation的API
wx.getSetting({
success: function(res) {
if (typeof(res.authSetting['scope.userLocation']) == "undefined") { // 从未触发过授权的情况
wx.getLocation({ // 用户同意授权地理位置
success: function(res) {
var locationString = res.latitude + "," + res.longitude;
wx.request({
url: 'http://apis.map.qq.com/ws/geocoder/v1/',
data: {
"key": "2IDBZ-O5OC3-WOB3U-YNDUM-WJ4J7-7PFHY",
"location": locationString
},
method: 'GET',
success: function(r) {
// 获取城市
let city = r.data.result.address_component.city
}
});
},
fail: function(err) { // 用户拒绝授权地理位置
wx.showModal({ //弹出模态框,询问
title: '是否授权当前位置',
content: '如需正常使用本程序,请按确定并在授权管理中选中“地理位置”,然后点按返回即可正常使用。',
cancelColor: '#f00',
success: function(res) {
if (res.confirm) { //同意授权
wx.openSetting({})
} else if (res.cancel) { //不同意授权,进行普通查询
}
}
})
}
})
}
}
})
} else {
//调用wx.getLocation的API
console.log('成功了')
wx.getLocation({ // 用户同意授权地理位置
success: function(res) {
var locationString = res.latitude + "," + res.longitude;
wx.request({
url: 'http://apis.map.qq.com/ws/geocoder/v1/',
data: {
"key": "2IDBZ-O5OC3-WOB3U-YNDUM-WJ4J7-7PFHY",
"location": locationString
},
method: 'GET',
success: function(r) {
// 获取城市
let city = r.data.result.address_component.city
}
});
}
})
}
}
})
网友评论