ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

vue3 vite 经纬度逆地址解析

2026/9/18 22:39:11 拓冰建站 浏览量
vue3 vite 经纬度逆地址解析

在web端测试经纬度逆地址解析有2中方式,先准备好两个应用key

第一种,使用“浏览器端”应用类型

const address = ref('')
const latitude = ref() // 经度
const longitude = ref() // 纬度
const ak = '你的key' // 浏览器端
function getAddressWeb() {// 创建地理编码实例      var myGeo = new BMapGL.Geocoder();// 根据坐标得到地址描述    myGeo.getLocation(new BMapGL.Point(longitude.value, latitude.value), (result) => {if (result) {address.value = result.address}});
}并在index.html插入script标签,引入百度地图sdk
<script type="text/javascript" src="https://api.map.baidu.com/api?v=1.0&&type=webgl&ak=你的key"></script>

第二种,使用“服务端”应用key

const ak = '你的key' // 服务器端
const latitude = ref() // 经度
const longitude = ref() // 纬度
const address = ref('')
function getAddressServe() {fetch(`/baidu?location=${latitude.value},${longitude.value}&output=json&coordtype=wgs84ll&ak=${ak}`).then(resp => resp.json()).then(res => {console.log(res);address.value = res.result.formatted_address;})
}

且需要配置vite.config.js文件的代理

server: {proxy: {'/baidu': {target: 'https://api.map.baidu.com/reverse_geocoding/v3/',changeOrigin: true,rewrite: (path) => path.replace(/^\/baidu/, ''),},},
},

如果你用“浏览器端”key测试服务器端会报240报错

{"status": 240,"message": "APP 服务被禁用"
}

不过需要注意的是,这两种方法都会导致你的key暴露,以上代码只做测试用不能用于线上发布,线上肯定还是要把key放在后端的。