最近在做毕设,遇到的这样一个问题,感觉比较重要,记录一下。
1 首先在项目的manifest.json文件如下位置添加代码
"permission": {
"scope.userLocation": {
"desc": "获取用户定位"
}
},
"requiredPrivateInfos": ["getLocation", "chooseLocation"]
2 导入高德提供的小程序插件
任意位置,导入common只是个人习惯
官方下载地址
3 注册高德开放平台账号,进入控制台添加应用
注意,在这里添加两个应用,第一个是实现基础的定位,第二个是实现点击地图实现选点定位
相关选择与我的对应
添加完成之后取key备用
4 准备工作完成,以下是实现代码,自行修改、测试
<template>
<view>
<button @click="getRegeo">点击进行定位</button>
<map style="width: 100%; height: 600rpx;" :latitude="latitude" :longitude="longitude" @tap="getCities">
</map>
<view>点击了:{{location}}</view>
</view>
</template>
<script>
// 导入高德的小程序插件
import amap from '@/common/amap-wx.130.js';
export default {
onLoad() {
this.amapPlugin = new amap.AMapWX({
key: this.key
});
},
data() {
return {
amapPlugin: null,
key: '第一个key',
key2: '第二个key',
longitude: '', //经度
latitude: '', //纬度
location: ''
}
},
methods: {
getRegeo() {
uni.showLoading({
title: '获取信息中'
});
this.amapPlugin.getRegeo({
success: (data) => {
console.log('正确数据', data[0])
this.longitude = data[0].longitude
this.latitude = data[0].latitude
uni.hideLoading();
},
fail(err) {
console.log('错误信息', err);
}
});
},
getCities(e) {
let that = this
uni.request({
header: {
'Content-Type': 'application/text',
},
//注意:这里的key值需要高德地图的 web服务生成的key 只有web服务才有逆地理编码
url: `https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${e.detail.longitude},${e.detail.latitude}&key=${this.key2}`,
success(res) {
console.log(res, "获取位置成功信息")
that.location = res.data.regeocode.formatted_address
},
fail(err) {
console.log(err, "获取位置失败信息")
}
})
}
}
}
</script>