因为需求需要获取用户当前的地理位置用于分析
通过原生的navigator.geolocation.getCurrentPosition获取经纬度
这个方法在谷歌浏览器会失效(原因未知),目前ie浏览器是可以获取的
getCurrentPosition() {
if (navigator.geolocation) {
var options = {
enableHighAccuracy: true, //布尔值,表示系统是否使用最高精度来表示结果,注意,这会导致较慢的响应时间或者增加电量消耗(比如对于支持gps的移动设备来说)。如果值为false ,设备会通过更快响应以及/或者使用更少的电量等方法来尽可能的节约资源。默认值fasle
timeout: 5000, //它表明的是设备必须在多长时间(单位毫秒)内返回一个位置。默认直到获取到位置才会返回值。
maximumAge: 0, //表明可以返回多长时间(即最长年龄,单位毫秒)内的可获取的缓存位置。如果设置为 0, 说明设备不能使用一个缓存位置,而且必须去获取一个真实的当前位置。默认0
};
navigator.geolocation.getCurrentPosition(
this.showPosition,
this.errorPosition,
options
);
} else {
this.errorPositionTxt = "不支持获取用户当前位置";
console.log("不支持获取用户当前位置");
}
},
showPosition(position) {
console.log(position);
console.log(position.coords);
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.getArea();
},
errorPosition(error) {
console.log(222);
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;
}
},
通过天地图根据经纬度获取详细地址
import axios from "axios";
getArea() {
axios({
method: "get",
url: "http://api.tianditu.gov.cn/geocoder",
params: {
tk: "放入自己申请的天地图的key",
type: "geocode",
postStr:
"{'lon':" +
this.longitude +
",'lat':" +
this.latitude +
",'ver':1}",
},
}).then((res) => {
console.log("数据:", res.data.result.addressComponent);
});
},