如何获取web用户地理位置信息

565 阅读1分钟

使用HTML5 Geolocation API

这是浏览器内置的标准化定位接口,通过JavaScript即可调用:

// 请求地理位置  
navigator.geolocation.getCurrentPosition(  
  //成功回调  
  (position) => {  
    console.log("纬度:", position.coords.latitude);  
    console.log("经度:", position.coords.longitude);  
    console.log("精度:", position.coords.accuracy"米");  
    console.log("时间戳:", position.timestamp);  
  },  
  //失败回调  
  (error) => {  
    console.error("错误代码:", error.code"错误信息:", error.message);  
    switch (error.code) {  
      case error.PERMISSION_DENIED:  
        console.log("用户拒绝了地理位置请求")  
        break  
      case error.POSITION_UNAVAILABLE:  
        console.log("位置信息不可用")  
        break  
      case error.TIMEOUT:  
        console.log("获取位置信息超时")  
        break  
      case error.UNKNOWN_ERROR:  
        console.log("发生未知错误")  
        break  
    }  
  },  
  // 配置项  
  {  
    enableHighAccuracytrue// 启用高精度模式(GPS)  
    timeout10000// 超时时间ms  
    maximumAge0// 不使用缓存位置  
  }  
)

注意事项:

此项功能仅在一些支持的浏览器的安全上下文(HTTPS)中可用。

只有经纬度吗?想要获取具体的位置怎么做呢?

通过Geolocation API确实只能得到经纬度等信息,想要获取具体的地点信息,就必须通过反向地理编码(Reverse Geocoding) 实现。

国外推荐Google Maps API

访问console.cloud.google.com/,创建项目 → 启用Geocoding API → 生成密钥

国内推荐使用高德/百度地图API

以高德地图举例

步骤:

  1. 注册高德开放平台

  2. 创建应用和key:具体操作步骤请点击这里

  3. 调用API,API具体说明请点击这里

/**  
 * @param lat 维度  
 * @param lng 经度  
 */  
async function getCityFromCoordinates(lat, lng) {  
  const KEY = "你的应用key";  
  const url = `https://restapi.amap.com/v3/geocode/regeo?location=${lng},${lat}&key=${KEY}&extensions=base`  
  
  const response = await fetch(url)  
  const data = await response.json()  
  
  return data.regeocode.formatted_address || "未知地区"  
}