HTML5 Geolocation API的正确使用方法

Geolocation是html5标准下的一个Web API,利用它可以获取设备的当前位置信息(坐标),此API具有三个方法:getCurrentPosition、watchPosition和clearWatch,其中最常用的是getCurrentPosition方法,剩下两个方法需要搭配使用!

使用方法:

浏览器兼容性检测:

该api通过navigator.geolocation对象发布,只有在此对象存在的情况下,才可以使用它的地理定位服务,检测方法如下:

if (navigator.geolocation) {    // 定位代码写在这里} else {    alert('Geolocation is not supported in your browser')}

获取用户的当前位置:

使用getCurrentLocation方法即可获取用户的位置信息,该方法有三个参数:

参数列表 类型 说明
handleSuccess Function 成功时调用函数handleSuccess
handleError Function 失败时调用函数handleError
options Object 初始化参数

// 初始化参数const options = {  // 高精确度: true / false  enableHighAccuracy: true,  // 等待响应的最长时间 单位:毫秒  timeout: 5 * 1000,  // 应用程序愿意接受的缓存位置的最长时间  maximumAge: 0}// 成功回调函数 : data包含位置信息const handleSuccess = data => console.log(data)// 失败回调函数 : error包含错误信息const handleError = error => console.log(error)if (navigator.geolocation) {    // 定位代码写在这里    navigator.geolocation.getCurrentPosition(handleSuccess, handleError, options)} else {    alert('Geolocation is not supported in your browser')}

下面是具有更多细节的代码:

const handleSuccess = data => {  const {     coords, // 位置信息    timestamp // 成功获取位置信息时的时间戳  } = data  const {    accuracy, // 返回结果的精度(米)    altitude, // 相对于水平面的高度    altitudeAccuracy, // 返回高度的精度(米)    heading, // 主机设备的行进方向,从正北方向顺时针方向    latitude, // 纬度    longitude, // 经度    speed // 设备的行进速度  } = coords  // 打印出来看看  console.log('timestamp =', timestamp)  console.log('accuracy =', accuracy)  console.log('altitude =', altitude)  console.log('altitudeAccuracy =', altitudeAccuracy)  console.log('heading =', heading)  console.log('latitude =', latitude)  console.log('longitude =', longitude)  console.log('speed =', speed)}const handleError = error => {  switch (error.code) {    case 1:      console.log('位置服务请求被拒绝')      break    case 2:      console.log('暂时获取不到位置信息')      break    case 3:      console.log('获取信息超时')      break    case 4:      console.log('未知错误')      break  }}const opt = {  // 高精确度: true / false  enableHighAccuracy: true,  // 等待响应的最长时间 单位:毫秒  timeout: 5 * 1000,  // 应用程序愿意接受的缓存位置的最大年限  maximumAge: 0}if (navigator.geolocation) {  navigator.geolocation.getCurrentPosition(handleSuccess, handleError, opt)} else {  alert('Geolocation is not supported in your browser')}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

相关文章

发表新评论