---
title: "<ScriptMapLibreGeolocateControl>"
description: "将 MapLibre 的定位按钮添加到最近的父级地图。该按钮会请求浏览器获取用户的位置，并将摄像机移动到该位置。"
canonical_url: "https://nuxt-scripts.zhcndoc.com/scripts/maplibre/api/geolocate-control"
last_updated: "2026-09-23T10:33:14.917Z"
---

将 MapLibre 的定位按钮添加到最近的父级地图。该按钮会请求浏览器获取用户的位置，并将摄像机移动到该位置。

```vue
<script setup lang="ts">
import type { ScriptMapLibreGeolocateControlEmits } from '@nuxt/scripts'

const message = ref('')

function onError(event: ScriptMapLibreGeolocateControlEmits['error'][0]) {
  message.value = event.code === 1 ? 'Location permission denied.' : event.message
}
</script>

<template>
  <ScriptMapLibreMap map-style="https://tiles.openfreemap.org/styles/liberty" :center="[147.33, -42.88]">
    <ScriptMapLibreGeolocateControl
      position="top-left"
      :options="{ trackUserLocation: true }"
      @error="onError"
      @unavailable="message = 'Location is not available in this browser.'"
    />
  </ScriptMapLibreMap>
  <p role="status">
    {{ message }}
  </p>
</template>
```

`new maplibregl.GeolocateControl()`{lang="ts"} 在创建控件时只读取一次 `options` 和 `position`。若要应用更改，请更改组件的 `key`。

组件会将 MapLibre 控件公开为 `control`。调用 `control.value.trigger()`{lang="ts"} 可通过代码请求位置信息。

## 事件

组件会使用 MapLibre 的事件对象触发每个 `GeolocateControl` 事件：

- 浏览器返回位置时会触发 `geolocate`。
- 浏览器返回错误时会触发 `error`。
- 位置超出地图的 `maxBounds` 时会触发 `outofmaxbounds`。
- 开始和停止追踪时会触发 `trackuserlocationstart` 和 `trackuserlocationend`。需要设置 `trackUserLocation`。
- 摄像机锁定到用户位置或离开用户位置时，会触发 `userlocationfocus` 和 `userlocationlostfocus`。

## 权限被拒绝

地理定位可能因两种情况失败。组件会报告这两种情况。

- 如果用户拒绝了权限提示，`error` 会以 `code` 1 触发。随后 MapLibre 会禁用该按钮。
- 如果控件加载时权限已被拒绝，MapLibre 会禁用该按钮，且不会触发任何事件。组件会以 `'permission-denied'` 触发 `unavailable`。
- 如果浏览器没有 Geolocation API，组件会以 `'unsupported'` 触发 `unavailable`。

地理定位需要安全上下文。在 `localhost` 以外的普通 HTTP 来源中，浏览器会拒绝地理定位。

::script-types{script-key="maplibre" filter="ScriptMapLibreGeolocateControl"}
::

## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
