1. 需去腾讯位置服务平台申请key并下载JavaScriptSDK
2. 在小程序管理后台 -> 开发 -> 开发管理 -> 开发设置 -> “服务器域名” 中设置request合法域名,添加https://apis.map.qq.com
3. 将解压后的文件放在common文件夹中
4. 在需要使用的页面中script引入const QQMapWX = require('@/common/qqmap-wx-jssdk.js');
5. 通过new QQMapWX({key:申请的key})
6. 获取到经纬度后进行转换qqMapSdk.reverseGeocoder({...})
<script>
const QQMapWX = require('@/common/qqmap-wx-jssdk.js');
export default {
data() {
return {
qqMapSdk: null,
city: '北京'
};
},
onShow() {
// 是否有选中城市
const choosedCity = uni.getStorageSync('choosedCity')
if(choosedCity){
this.city = choosedCity
uni.removeStorageSync('choosedCity')
} else {
this.qqMapSdk = new QQMapWX({
key: '申请的key'
});
this.getUserLocation()
}
},
methods: {
// 获取位置信息
getUserLocation() {
uni.getLocation({
type: 'wgs84',
success: (res) => {
this.formatLocation(res.latitude,res.longitude)
},
fail: (res) => {
if (res.errMsg == "getLocation:fail auth deny"){
uni.showModal({
content: '检测到您没打开获取信息功能权限,是否去设置打开?',
confirmText: "确认",
cancelText: '取消',
success: (res) => {
if (res.confirm) {
uni.openSetting({
success: (res) => {
console.log('确定');
}
})
} else {
console.log('取消');
return false;
}
}
})
}
}
})
},
// 转换城市
formatLocation(latitude, longitude) {
this.qqMapSdk.reverseGeocoder({
location: {
latitude,
longitude
},
success: (res) => {
let cityName = res.result.address_component.city
this.city=cityName.slice(0,cityName.length-1)
},
fail: () => {
this.city = '北京'
}
})
},
}
}
</script>