一、场景
希望点击一个按钮,获取当前设备的位置信息,经纬度。
二、获取 使用MDN 提供的方法
不多说,一个方法直接获取到经纬度:
Geolocation.getCurrentPosition() 方法用来获取设备当前位置。
navigator.geolocation.getCurrentPosition(res=>{
console.log(`res`, res)
// res=> GeolocationPosition{
// coords:{
// accuracy: 20185 // 准确度
// altitude: null // 高度
// altitudeAccuracy: null
// heading: null
// latitude: 22.3193039 // 纬度
// longitude: 114.16936109999999 // 经度
// },
// timestamp: 1619592517698, // 时间戳
// }
})
三、拓展
完整的方法应该是包含了✅正确的处理、❌错误的处理、还有配置option;
getad() {
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
}
function success(pos) {
console.log(`pos`, pos)
const crd = pos.coords;
console.log('Your current position is:');
console.log('Latitude : ' + crd.latitude);
console.log('Longitude: ' + crd.longitude);
console.log('More or less ' + crd.accuracy + ' meters.');
}
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
}
navigator.geolocation.getCurrentPosition(success, error, options);
}