最近接了个需求,要在前端页面实现用户终端地理位置定位的功能,直接就想到了使用 HTML5 提供的 Geolocation API 来实现:
navigator.geolocation.getCurrentPosition(
({ coords: { latitude, longitude } }) => {
document.getElementById("h5-position").innerHTML = `
latitude: ${latitude}
<br>
longitude: ${longitude}
`;
},
(e) => {
console.error(e);
},
{ enableHighAccuracy: true }
);
但在测试过程中,发现 H5 地理位置定位存在较大的误差,有时误差甚至超过了 500m ,这显然难以满足我们的要求。于是寻找解决方案。
查阅腾讯地图的开发文档,发现了腾讯地图提供了一个前端定位的 SDK:
https://lbs.qq.com/webApi/component/componentGuide/componentGeolocation
据文档描述该 SDK 可以提升前端定位准确度,于是做了一个试验来对 HTML5 的定位 API 和腾讯地图的定位 SDK 的精确度进行比较。
试验的代码实现如下:
<!-- 页面代码 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<!-- 引入腾讯地图 SDK -->
<script src="https://mapapi.qq.com/web/mapComponents/geoLocation/v/geolocation.min.js">