<template>
<section class="index">
<h2>获取用户当前位置</h2>
<div class="">{{ errorPositionTxt }}</div>
<div class="">纬度 latitude:{{ latitude }}</div>
<div class="">经度 longitude:{{ longitude }}</div>
</section>
</template>
<script>
export default {
data() {
return {
latitude: "",
longitude: "",
errorPositionTxt: ""
};
},
created() {
this.getCurrentPosition();
},
methods: {
getCurrentPosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
this.showPosition,
this.errorPosition
);
} else {
this.errorPositionTxt = "不支持获取用户当前位置";
console.log("不支持获取用户当前位置");
}
},
showPosition(position) {
console.log(position);
console.log(position.coords);
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
},
errorPosition(error) {
switch (error.code) {
// 不允许获取当前位置
case error.PERMISSION_DENIED:
this.errorPositionTxt = "不允许获取当前位置";
break;
// 无法获取当前位置
case error.POSITION_UNAVAILABLE:
this.errorPositionTxt = "无法获取当前位置";
break;
// 获取位置的请求超时。
case error.TIMEOUT:
this.errorPositionTxt = "获取位置请求超时。";
break;
// 获取位置操作超时
case error.UNKNOWN_ERROR:
this.errorPositionTxt = "获取位置操作超时";
break;
}
}
}
};
</script>
<style scoped lang="scss"></style>