uniapp通过百度地图API获取手机定位及地址
先获取手机的定位(WGS84)坐标,然后转为BD09坐标,然后通过逆地址编码获取到地址:
完整代码如下:
步骤一:
在manifest.json中加入百度地图的ak,并且勾选上
步骤二:
在pages.json中加入扩展的信息:
步骤三:
完整的代码如下:
<template>
<view class="container">
<button @click="fetchLocation">获取位置</button>
<text>当前位置(WGS84):{{ location.latitude }}, {{ location.longitude }}</text>
<text>百度坐标(BD09):{{ bdLocation.latitude }}, {{ bdLocation.longitude }}</text>
<text>地址信息:{{ address }}</text>
</view>
</template>
<script>
export default {
data() {
return {
location: {
latitude: 0,
longitude: 0,
},
bdLocation: {
latitude: 0,
longitude: 0,
},
address: '正在获取...',
};
},
methods: {
fetchLocation() {
uni.getLocation({
type: 'wgs84', // 获取 GPS 坐标
success: (res) => {
console.log('获取到的WGS84坐标:', res.latitude, res.longitude);
this.location = {
latitude: res.latitude,
longitude: res.longitude,
};
this.convertToBD09(res.latitude, res.longitude);
},
fail: (err) => {
console.error('获取位置信息失败', err);
this.address = '获取位置信息失败';
},
});
},
convertToBD09(gcjLat, gcjLng) {
// 使用百度地图的坐标转换服务
const url = `https://api.map.baidu.com/geoconv/v1/?coords=${gcjLng},${gcjLat}&from=1&to=5&ak=替换为自己的ak值`;
uni.request({
url: url,
success: (res) => {
if (res.data.status === 0) {
const bdLocation = res.data.result[0];
this.bdLocation = {
latitude: bdLocation.y,
longitude: bdLocation.x,
};
console.log('转换后的BD09坐标:', this.bdLocation.latitude, this.bdLocation.longitude);
this.getReverseGeocoding(this.bdLocation.latitude, this.bdLocation.longitude);
} else {
console.error('坐标转换失败:', res.data.message);
this.address = '坐标转换失败';
}
},
fail: (err) => {
console.error('坐标转换请求失败', err);
this.address = '坐标转换请求失败';
},
});
},
getReverseGeocoding(lat, lng) {
// 使用百度地图的逆地理编码服务
const url = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=替换为自己的ak值&location=${lat},${lng}&output=json`;
uni.request({
url: url,
success: (res) => {
if (res.data.status === 0) {
const address = res.data.result.formatted_address;
this.address = address;
console.log('地址信息:', address);
} else {
console.error('逆地理编码失败:', res.data.message);
this.address = '逆地理编码失败';
}
},
fail: (err) => {
console.error('逆地理编码请求失败', err);
this.address = '逆地理编码请求失败';
},
});
},
},
};
</script>
注意替换为自己的百度地图的api,以及自己的ak的值
链接手机,并运行获取到的结果:
逆地址编码失败的原因如下:
请前往百度地图api中开启移动应用场景:
获取到的坐标去第三方网址上检验:
第三方地址:
http://jingweidu.757dy.com/
到此完成