WeChat's getLocation interface can obtain the user's longitude and latitude information, but there is no way to obtain the province, city, and county street information, so you need to use AutoNavi's API interface to convert the longitude and latitude into province, city, and county information. When docking, there are There are two ways to connect to this interface. One is to use Amap's web service, and the other is to use the WeChat applet SDK. Because the SDK will increase the size of the applet, I chose the web service.
Apply for Amap KEY
In the background of AMAP, first create an application, and then apply for a web service key:https://console.amap.com/dev/key/app< /span>
Copy key to applet
Copy the key of the created web service into the applet
Replace the key in the code below
uni.getLocation({
geocode: true, // 返回经纬度
success: function (loction) {
console.log("getLocation", loction);
// 将经纬度转换为城市数据
uni.request({
url: 'https://restapi.amap.com/v3/geocode/regeo',
method: 'GET',
data: {
key: '高德WEB服务key',
location: loction.longitude + ',' + loction.latitude
},
success: (resda: any) => {
console.log("resda", resda)
const { province, district } = resda.data.regeocode.addressComponent
CityName.value = province
uni.navigateBack()
},
fail: (err: any) => {
console.log("restapi err", err);
}
})
}
})
Then send a request to see the result: