js怎么获取设备的地理位置

本文介绍了如何通过JavaScript的Geolocation API获取设备的当前位置信息,包括经纬度。使用`navigator.geolocation.getCurrentPosition()`方法可以简单直接地获取到位置,并提供了包含正确处理、错误处理及配置选项的完整示例。在获取位置时,还可以设置精度、超时和缓存等选项。
摘要由CSDN通过智能技术生成

一、场景

希望点击一个按钮,获取当前设备的位置信息,经纬度。

二、获取 使用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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值