Vue 获取当前位置
1. 封装获取位置的方法(注意要在https才生效)
#vim resources/src/utils/geo.js
function getPosError(err) {
console.log(err)
}
export function getLocation(getPosSuccess) {
if (navigator.geolocation) {
let options = {
enableHighAccuracy: true, maximumAge: 30000, timeout: 12000
}
navigator.geolocation.getCurrentPosition(getPosSuccess, getPosError, options);
} else {
console.log('当前环境不支持')
}
}
2. 在需要的地方调用
import {getLocation} from "@/utils/geo";
function getPosSuccess(pos) {
console.log(`纬度:${pos.coords.latitude} 经度:${pos.coords.longitude}`)
}
getLocation(getPosSuccess);
打开console可以看到:
然后通过经纬度获取具体地址或者其他信息获取可以通过第三方接口。