1、注册腾讯地址api接口,创建应用获取key
WebService API | 腾讯位置服务
2、配置获取方法getCity
// 定位服务
getCity(latitude, longitude) {
const key = 'XXXX-XXXX-XXXX-XXXX-XXXX'; // 替换为你的腾讯位置服务密钥
const url = `/apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}`;
uni.request({
url: url,
success: (res) => { // 使用箭头函数,确保 `this` 指向当前组件
console.log(res);
if (res.statusCode === 200) {
const city = res.data.result.address_component.city;
console.log('定位到的城市是:', city);
} else {
console.error('逆地理编码失败:', res.data.message);
}
},
fail: (err) => {
console.error('请求失败:', err);
}
});
},
3、在页面加载时调用api获取地址
onLoad() {
uni.getLocation({
type: 'wgs84', // 默认使用 gcj02 坐标系
success: (res) => {
console.log('经度:' + res.longitude);
console.log('纬度:' + res.latitude);
// 调用逆地理编码服务,传递经纬度
// console.log(this);
this.getCity(res.latitude, res.longitude); // 使用 `this` 引用方法
},
fail: function (err) {
console.error('获取位置失败:', err);
}
});
},