欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > uniapp通过百度地图API获取手机定位及地址

uniapp通过百度地图API获取手机定位及地址

2025/6/23 1:19:09 来源:https://blog.csdn.net/weixin_41823246/article/details/148734393  浏览:    关键词:uniapp通过百度地图API获取手机定位及地址

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/
在这里插入图片描述
到此完成

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词