一个「使用我的位置」按钮,能让用户免去手输地址、搜索地点,或者从别的应用里复制坐标的麻烦。

对地图应用来说,它也是个不错的起点:拿到用户的经纬度,再用这组坐标去放标记、查地址,或者搜附近的地点。

这篇教程会做一个浏览器小例子:点按钮后请求位置、显示结果、处理常见错误,再生成一个能在 Google Maps 里打开这组坐标的链接。

一、从浏览器的 Geolocation API 开始

浏览器提供的 Geolocation API 通过 navigator.geolocation 暴露。只取一次位置时,用 getCurrentPosition()。

它接收成功回调、错误回调,以及一个可选的配置对象:

navigator.geolocation.getCurrentPosition(
  (position) => {
    const { latitude, longitude } = position.coords;
    console.log({ latitude, longitude });
  },
  (error) => {
    console.error(error.code, error.message);
  },
  {
    enableHighAccuracy: true,
    timeout: 10000,
    maximumAge: 0,
  }
);

调用是异步的。坐标在成功回调里拿到,不是方法的返回值。

部署到线上要用 HTTPS。用户得允许位置访问,站点的 Permissions Policy 也可能把这个功能挡掉。本地开发用的 http://localhost 通常被视为潜在可信来源。

二、做一个完整的例子

把下面这段存成 index.html,再用 localhost 或 HTTPS 把它跑起来。

页面只在你点按钮时才请求位置。请求进行中会禁用按钮,失败时会给出看得懂的提示。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Find My Current Coordinates</title>
</head>
<body>
  <main>
    <h1>Find My Current Coordinates</h1>
    <p>Allow location access to see your latitude and longitude.</p>

    <button id="locate" type="button">Use my location</button>
    <p id="status" role="status" aria-live="polite"></p>

    <section id="result" hidden>
      <h2>Your reported location</h2>
      <dl>
        <dt>Latitude</dt>
        <dd id="latitude"></dd>
        <dt>Longitude</dt>
        <dd id="longitude"></dd>
        <dt>Estimated accuracy radius</dt>
        <dd id="accuracy"></dd>
        <dt>Position timestamp</dt>
        <dd id="timestamp"></dd>
      </dl>
      <a id="map-link" target="_blank" rel="noopener noreferrer">
        Open in Google Maps
      </a>
    </section>
  </main>

  <script>
    const button = document.querySelector("#locate");
    const status = document.querySelector("#status");
    const result = document.querySelector("#result");
    const mapLink = document.querySelector("#map-link");

    const errorMessages = {
      1: "Location access was denied or blocked. Check site permissions, or enter coordinates manually.",
      2: "Your device could not determine a position. Check location services and try again.",
      3: "The location request timed out. Try again, or enter coordinates manually.",
    };

    button.addEventListener("click", () => {
      result.hidden = true;
      mapLink.removeAttribute("href");

      if (!window.isSecureContext) {
        status.textContent = "Open this page over HTTPS or on localhost.";
        return;
      }

      if (!navigator.geolocation) {
        status.textContent = "Geolocation is unavailable in this browser.";
        return;
      }

      button.disabled = true;
      status.textContent = "Requesting your location. Please respond to any permission prompt.";

      navigator.geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude, accuracy } = position.coords;

          document.querySelector("#latitude").textContent = latitude.toFixed(6);
          document.querySelector("#longitude").textContent = longitude.toFixed(6);
          document.querySelector("#accuracy").textContent = `${Math.round(accuracy)} meters`;
          document.querySelector("#timestamp").textContent =
            new Date(position.timestamp).toLocaleString();

          const url = new URL("https://www.google.com/maps/search/");
          url.searchParams.set("api", "1");
          url.searchParams.set("query", `${latitude},${longitude}`);
          mapLink.href = url.toString();

          result.hidden = false;
          status.textContent = "Location received. Check the accuracy estimate before using it.";
          button.disabled = false;
        },
        (error) => {
          status.textContent =
            errorMessages[error.code] || "Unable to get your location. Please try again.";
          button.disabled = false;
        },
        {
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 0,
        }
      );
    });
  </script>
</body>
</html>

比如装了 Python,就在文件所在目录起一个本地服务:

python -m http.server 8000

本机实跑:python -m http.server 8000 起本地服务并返回 200

然后打开 http://localhost:8000。用本地服务打开文件,比依赖 file:// 的行为更好预测。

这个例子只在本地显示坐标,不会把它上传到应用服务器。点 Google Maps 链接时,坐标会作为 URL 参数发给 Google Maps。

三、按场景挑选配置项

上面的配置偏向拿到新结果、要更高精度。把人标到地图上时这么设挺合适,但不是每个功能都该这么配。

配置项 示例值 作用
enableHighAccuracy true 请求更高精度,代价可能是更多耗时和耗电
timeout 10000 把获取位置的时间限制在 10 秒
maximumAge 0 要求返回全新位置,不接受缓存结果

获取超时不包含等待授权、等待文档变为可见的时间。所以用户要是把授权弹窗晾着不点,等待可能超过十秒。

做「附近城市」这类功能时,可以考虑允许用刚缓存不久的位置:

const options = {
  enableHighAccuracy: false,
  timeout: 10000,
  maximumAge: 60000,
};

这样浏览器就能复用最长一分钟前的位置。按结果要多新、多精确来挑配置。

各配置项的定义可以查 MDN 的 getCurrentPosition 文档和 W3C Geolocation 规范。

四、把精度和坐标一起显示

实际位置不确定时,一组坐标看着也可能很精确。

比如显示到小数点后六位,并不能证明设备真能定位到这个精度。例子里的 toFixed(6) 只管显示。

浏览器给出的 accuracy 属性提供水平精度估计,单位是米,按 95% 置信度给出。

报出来的半径是 20 米还是 2000 米,界面该怎么设计不一样。半径大时,地图可以把范围放得更大,让用户自己微调位置。

浏览器定位也不保证拿到 GPS 读数。设备和浏览器会自己挑可用的定位来源。把它当成一个带精度估计的上报位置就好。

五、把位置标到 MapLibre 地图上

应用里要是已经有初始化好的 MapLibre GL JS 地图,可以在成功回调里加一个标记。

假设 maplibregl 可用,map 指向你的地图实例。标记变量在回调外面声明一次:

let userMarker;

// Call this from the geolocation success callback.
function showUserLocation(position) {
  const { latitude, longitude } = position.coords;

  // MapLibre expects longitude first.
  const lngLat = [longitude, latitude];

  if (userMarker) {
    userMarker.setLngLat(lngLat);
  } else {
    userMarker = new maplibregl.Marker()
      .setLngLat(lngLat)
      .addTo(map);
  }

  map.setCenter(lngLat);
}

更新已有标记,能避免反复点按钮时冒出一堆重复标记。

留意坐标顺序。HTML 例子里 Google Maps 的搜索查询用 latitude,longitude,MapLibre 用 [longitude, latitude]。MapLibre 的 Marker 文档对 setLngLat() 方法有说明。

六、把错误处理做进界面

GeolocationPositionError 的错误码对应三种常见失败情况:

错误码 名称 合适的应对
1 PERMISSION_DENIED 说明访问被拒或被拦;提供手动输入
2 POSITION_UNAVAILABLE 提示检查设备定位服务后重试
3 TIMEOUT 提供重试,以及另一种选位置的方式

权限被拒不一定意味着用户刚点了「阻止」。访问权可能早就被拒了,或者被某条策略挡住。

被拒后别自动重试。把主动权留给用户,给条替代路子:搜地址、输坐标,或者在地图上选点。

七、拿到坐标后做下一步

拿到经纬度后,再决定用户下一步要做什么。

查地址要逆地理编码;搜附近地点要给个搜索半径;放地图标记要按地图库要求的坐标顺序来。

对「使用我的位置」这个功能来说,好用的第一版不必大:一个明确的按钮、一个带精度估计的位置、一个地图动作,再加一条位置拿不到时清清楚楚的退路。


如果这篇帮你少踩了坑,点个赞、收藏一下,下次要用时好翻。关注「山岚的运维笔记」,继续看更多前端实战。