<template>
<view class="content">
<view class="text" v-if="address">{{ address }}</view>
<view v-else>获取位置中...</view>
</view>
</template>
<script>
export default {
data() {
return {
address: '', // 用于存储地址信息
latitude: 0, // 纬度
longitude: 0 // 经度
};
},
onLoad() {
this.getLocation();
},
methods: {
// 获取地理位置的方法
getLocation() {
uni.getLocation({
type: 'gcj02',
success: (res) => { // 使用箭头函数保持this指向
console.log('纬度:' + res.latitude);
console.log('经度:' + res.longitude);
// 可以将获取到的经纬度信息保存到data中,然后在页面上显示
this.latitude = res.latitude;
this.longitude = res.longitude;
this.getAddress(this.latitude, this.longitude); // 获取地址
},
fail: () => {
uni.showToast({
title: '获取位置失败,将导致部分功能不可用',
icon: 'none'
});
}
});
},
// 根据经纬度获取地址的方法
getAddress(latitude, longitude) {
const key = 'e3982bcf082fbe63015fe5034931f117';
uni.request({
url: `https://restapi.amap.com/v3/geocode/regeo?key=${key}&batch=false&location=${longitude},${latitude}`,
method: 'GET',
success: (res) => {
if (res.data.status === '1' && res.data.regeocode) {
let address = res.data.regeocode.formatted_address;
this.address = address;
} else {
console.error('逆地理编码失败');
}
},
fail: () => {
console.error('请求地址信息失败');
}
});
}
}
};
</script>
<style>
.content {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
</style>
需要传入自己的高德key值:我的应用 | 高德控制台 创建应用 选择web服务来获取key值
注:需要注意经纬度的顺序 先传递经度 再传递纬度