uni-app 实现市级定位
<template>
<view class=""> </view>
</template>
<script>
export default {
data() {
return {};
},
onl oad(option) {
const self = this;
self.getLocation();
},
methods: {
async getLocation() {
const self = this;
const { latitude, longitude } = await self.getLocationByUniAPI();
const resp = await self.getAddressInfo(latitude, longitude);
const city = await self.getCityFromAddressInfo(resp);
},
// 通过 uni-app API 获取经纬度定位
getLocationByUniAPI() {
return new Promise((resolve, reject) => {
uni.getLocation({
type: "wgs84",
success: function (res) {
resolve({
longitude: res.longitude,
latitude: res.latitude,
});
},
fail(res) {
reject(res);
},
});
});
},
// 通过高德的逆地理解析接口解析经纬度所在地址
getAddressInfo(latitude, longitude) {
return new Promise((resolve, reject) => {
uni.request({
url: `https://restapi.amap.com/v3/geocode/regeo?location=${longitude},${latitude}&key=<your key>`,
success: function (res) {
resolve(res.data);
},
fail: function (res) {
console.log(res);
reject("逆地址解析失败");
},
});
});
},
// 从地址信息中获取所在城市
getCityFromAddressInfo(addressInfo) {
let retCity = "";
if (addressInfo.status === "1") {
const addressComponent = addressInfo.regeocode.addressComponent;
if (Array.isArray(addressComponent.city)) {
if (addressComponent.citycode.length === 3) {
// citycode 为3位时,直辖市,取省份字段
retCity = addressComponent.province;
} else {
// citycode 为4位时,省直辖县,取地区字段
retCity = addressComponent.district;
}
} else {
retCity = addressComponent.city;
}
} else {
uni.showToast({
title: "逆地址解析失败",
icon: "none",
duration: 3000,
});
}
return retCity;
},
},
};
</script>
<style scoped></style>
标签:市级,const,addressComponent,res,app,latitude,uni,self
From: https://www.cnblogs.com/yuzhihui/p/17237286.html