uni-app微信小程序如何使用高德地图。通过经纬度获取所在城市,涉及到授权获取地理位置权限
·
高德地图官方是这样介绍的使用方法可以参考:入门指南-微信小程序插件 | 高德地图API
我再介绍一下我得具体应用。
1,首先要在申请高德地图开放平台得账号。然后在这个账号中申请一个应用。类型选择微信小程序。
获取Key-创建工程-开发指南-微信小程序插件 | 高德地图API

点击提交我们就得到一个可以看的key得应用啦。

下载之后你会得到一个压缩文件
解压缩后得到一个amap-wx.130.js。把他放到自己的项目里面。
4,
因为他最后是通过
module.exports.AMapWX=AMapWX;得方式导出的。如果在vue3项目种我们通过var amapFile = require('@/js_sdk/amap/amap-wx.130.js');得方式引入他会报错
vendor.js? [sm]:2643 Error: module 'components/get-location/@/js_sdk/amap/amap-wx.130.js' is not defined, require args is '@/js_sdk/amap/amap-wx.130.js'

于是我修改了amap-wx.130.js得导出方式。把module.exports.AMapWX=AMapWX;改成export default{ AMapWX };
然后引入方式改成import就可以了。
import {onLoad, onInit, onShow} from "@dcloudio/uni-app";
import {ref} from "vue";
import amapFile from "@/js_sdk/amap/amap-wx.130.js"
const nowCity = ref('');
onLoad((options: any) => {
checkauthorize();
})
const checkauthorize = () => {
uni.getSetting({
success(res) {
if (!res.authSetting['scope.userLocation']) {
uni.authorize({
scope: 'scope.userLocation',
success: () => { //这里是用户同意授权后的回调
getLocation();
},
fail: () => { //这里是用户拒绝授权后的回调
rejectSetting()
}
})
} else { //用户已经授权过了
getLocation();
}
}
})
}
const getLocation = () => {
uni.getLocation({
type: 'wgs84',
success: function (res) {
console.log(res)
console.log('经度:' + res.longitude);
console.log('纬度:' + res.latitude);
getAddress(res.latitude,res.longitude);
}
});
}
//经纬度转换成省市区 latitude纬度,long经度
const getAddress=(latitude, longitude)=>{
let myAmapFun = new amapFile.AMapWX({ key: "高德地图的key值" });
myAmapFun.getRegeo({
location: '' + longitude + ',' + latitude + '',//location的格式为'经度,纬度'
success: function (data) {
console.log("转换成省市",data);
let {province,city,district} = data[0].regeocodeData.addressComponent;
city = (city || city?.length>0) ? city:"";
console.log(city)
nowCity.value=city;
uni.setStorageSync('city',nowCity.value)
console.log("省市区:",province+city+district)
},
fail: function (info) { }
})
}
//用户拒绝授权后的回调
const rejectSetting = () => {
var that = this;
uni.showModal({
title: '警告',
content: '授权失败,请打开位置消息授权',
success: (res) => {
if (res.confirm) { //去授权
toOpenSetting();
} else if (res.cancel) {//用户点击取消
console.log(res);
uni.showModal({
title: '提示',
content: '获取权限失败,将无法获取定位哦~',
showCancel: false,
success: (res) => {
toOpenSetting();
}
})
}
}
})
}
//打开微信设置页面
const toOpenSetting = () => {
uni.openSetting({
success: (e) => {
console.log(e);
}
})
}
同时还有一些地方要改。
1,首先微信开放平台得小程序后台设置。开发管理-接口权限。开通获取当前的地理位置。
因为这个小程序的类目不在申请的列表里。所以下图显示的是没有权限。如果你也是这样的情况可以先去添加小程序的类目(首页-小程序类目-查看详情)


2,开发管理-开发设置里面添加request合法域名: https://restapi.amap.com

3.代码里面要添加manifest.json里面加
"permission" : {
"scope.userLocation" : {
"desc" : "展示位置"
}
}

4.代码里面。page.json在使用地图的页面加上
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
}

小程序中回调起询问会话框。点击允许就能获取地理位置了


更多推荐



所有评论(0)