需求:
1.在进入页面时,请求用户地理位置授权,获取用户当前的地理位置;
2.获取用户的经纬度,有时候需要通过经纬度来计算用户与店铺之间的距离;
步骤:
1.微信小程序后台将域名添加到当前使用的APPID域名里面;
2.下载qqmap.wx-jssdk.js和qqmap.wx-jssdk.min.js包,放在小程序所在的文件夹里面;
3.在需要获取用户地理位置的页面顶部,请求下载的包;
代码:
var QQMapWX = require('../qqmap-wx-jssdk.js');
var qqmapsdk = new QQMapWX({
key: '小程序密钥' // 必填
});
4.具体实现的代码:
//在onload里面执行getUserLocation这个函数
//获取用户地理位置
getUserLocation: function () {
let vm = this;
wx.getSetting({
success: (res) => {
console.log(JSON.stringify(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) {
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
vm.getLocation();
} else {
wx.showToast({
title: '授权失败',
icon: 'none',
duration: 1000
})
}
}
})
}
}
})
} else if (res.authSetting['scope.userLocation'] == undefined) {
//调用wx.getLocation的API
vm.getLocation();
} else {
//调用wx.getLocation的API
vm.getLocation();
}
}
})
},
// 微信获得经纬度
getLocation: function () {
let vm = this;
wx.getLocation({
type: 'wgs84',
success: function (res) {
console.log(JSON.stringify(res))
var latitude = res.latitude
var longitude = res.longitude
var speed = res.speed
var accuracy = res.accuracy;
vm.getLocal(latitude, longitude)
vm.setData({
latitude: latitude,
longitude: longitude
})
},
fail: function (res) {
console.log('fail' + JSON.stringify(res))
}
})
},
// 获取当前地理位置
getLocal: function (latitude, longitude) {
let vm = this;
qqmapsdk.reverseGeocoder({
location: {
latitude: latitude,
longitude: longitude
},
success: function (res) {
console.log(res)
wx.setStorageSync("location", res.result.address_component);
let province = res.result.ad_info.province;
let city = res.result.ad_info.city;
vm.setData({
province: province,
city: city,
latitude1: latitude,
longitude1: longitude
})
},
fail: function (res) {
console.log(res);
},
complete: function (res) {
console.log(res);
var latitudeArr = res.result.location;
console.log(latitudeArr)
vm.setData({
latitudeArr: latitudeArr
})
}
});
},
热爱前端,热爱编程,热爱分享,欢迎一起聊各种技术问题,一起进步,一起成长!微信:zhan_1337608148