经纬志
首页 / MapLibre / API 文档

GeolocateControl

先看结论

定位按钮,调用浏览器 Geolocation API 找到用户位置,可单次定位,也可持续跟随。

最后验证 2026-11-03 · MapLibre GL JS 4.x · 更新 2026-10-28 · 引用本文
map.addControl(new maplibregl.GeolocateControl({ trackUserLocation: true }), 'top-right')

参数

字段默认说明
positionOptions{enableHighAccuracy: false, timeout: 6000}透传给 getCurrentPosition
fitBoundsOptions{maxZoom: 15}定位后跳转视角的参数
trackUserLocationfalsetrue 时持续监听位置变化
showAccuracyCircletrue画精度圈;showUserLocation 为 false 时无效
showUserLocationtrue显示代表当前位置的圆点

成员与事件

成员说明
trigger()以程序方式触发一次定位,等同点击按钮
onAdd(map)创建按钮并插入控件容器
onRemove(map)停止监听并移除按钮
geolocate 事件拿到位置,coords 含经纬度与精度
error 事件拒绝授权、超时或定位不可用
outofmaxbounds 事件定位点落在地图 maxBounds 之外
trackuserlocationstart进入跟随状态
trackuserlocationend退出跟随状态

示例

var locate = new maplibregl.GeolocateControl({
  positionOptions: {
    enableHighAccuracy: true,
    timeout: 10000,
    maximumAge: 0
  },
  fitBoundsOptions: { maxZoom: 16 },
  trackUserLocation: true,
  showAccuracyCircle: true,
  showUserLocation: true
});

map.addControl(locate, 'top-right');

map.on('geolocate', function (e) {
  var lng = e.coords.longitude.toFixed(5);
  var lat = e.coords.latitude.toFixed(5);
  document.getElementById('pos').textContent = lng + ', ' + lat;
});

map.on('error', function (e) {
  if (e.error && e.error.code === 1) {
    console.warn('用户拒绝了定位授权');
  }
});

/* 页面有明确按钮时,不必依赖控件图标 */
document.getElementById('locate-btn').addEventListener('click', function () {
  locate.trigger();
});

注意事项

定位要求在安全上下文中运行,http 页面里浏览器直接拒绝, 连授权弹窗都不会出现。本地调试用 localhost, 线上必须是 https。

enableHighAccuracy: true 会启用 GPS,首次定位可能等十几秒。 对精度要求不高的签到场景保持默认的 false, 用基站或 Wi-Fi 定位,速度快得多。

跟随状态与用户操作。开启 trackUserLocation 后, 用户一旦拖动地图,控件自动退到后台状态,只更新点位不抢镜头。 这个切换会触发 trackuserlocationend,可在其中提示「已暂停跟随」。

引用本文

经纬志(2026)。《GeolocateControl》。https://www.jingweizhi.com/maplibre/api/geolocate-control.html(访问日期 2026-11-03)。