当前位置: 移动技术网 > IT编程>网页制作>Html5 > HTML5 Geolocation API的正确使用方法

HTML5 Geolocation API的正确使用方法

2019年07月25日  | 移动技术网IT编程  | 我要评论

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')
}

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网