vue2 实现已知经纬度获取位置
时间: 2023-09-12 18:13:14 浏览: 80
你可以使用 HTML5 的 Geolocation API 来获取用户的当前位置,然后使用第三方的地图 API 来通过经纬度获取位置信息。下面是一个使用 Vue2 实现已知经纬度获取位置的示例代码:
```html
<template>
<div>
<p>经度:{{ longitude }}</p>
<p>纬度:{{ latitude }}</p>
<p>位置:{{ location }}</p>
</div>
</template>
<script>
export default {
data() {
return {
longitude: null,
latitude: null,
location: null
};
},
mounted() {
navigator.geolocation.getCurrentPosition(position => {
// 获取经度和纬度
this.longitude = position.coords.longitude;
this.latitude = position.coords.latitude;
// 调用地图 API 获取位置信息
this.getLocation(this.longitude, this.latitude);
});
},
methods: {
getLocation(longitude, latitude) {
const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=YOUR_KEY`;
// YOUR_KEY 替换成你自己的密钥
fetch(url)
.then(res => res.json())
.then(data => {
this.location = data.result.address;
})
.catch(error => {
console.error(error);
});
}
}
};
</script>
```
需要注意的是,这里使用的是腾讯地图 API,需要替换成你自己的密钥。另外,为了使代码更加简洁,这里使用了 ES6 的箭头函数和 fetch 方法,如果你需要兼容老版本的浏览器,可以改为普通的函数和 XMLHttpRequest。