获取定位信息
<template>
<div id="app"></div>
</template>
<script>
export default {
data() {
return {
latitude: undefined, //维度
longitude: undefined, //经度
positionWatcher: null,
};
},
mounted() {
this.getGeolo();
},
beforeDestroy() {
//清除浏览器持续定位
if (this.positionWatcher) {
navigator.geolocation.clearWatch(this.positionWatcher);
}
},
methods: {
async getGeolo() {
// 根据navigator api获取经纬度 在浏览器环境中
await new Promise((resolve, reject) => {
if (navigator.geolocation) {
//获取地理位置
navigator.geolocation.getCurrentPosition(
(position) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
console.log("浏览器获取坐标 => ", position.coords);
resolve(position.coords);
},
(error) => {
reject(error);
},
{
enableHighAccuracy: true, //获取高精度经纬度
coordsType: "gcj02", //使用国测局经纬度坐标系
}
);
//持续定位
this.positionWatcher = navigator.geolocation.watchPosition(
(position) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
console.log("浏览器持续获取坐标 => ", position.coords);
},
(error) => {
console.info("浏览器持续定位出错 => ", error);
},
{
enableHighAccuracy: true, //获取高精度经纬度
coordsType: "gcj02", //使用国测局经纬度坐标系
}
);
} else {
console.info("无法获取地理位置信息");
reject();
}
})
.then()
.catch((err) => {
console.info("浏览器获取经纬度失败 => ", err);
});
},
},
};
</script>
<style lang="scss">
html,
body {
height: 100%;
margin: 0px;
padding: 0px;
}
#app {
}
</style>