---
title: "useMapbox"
description: "按 id 从注册表获取已挂载地图的上下文，在组件树之外或跨路由访问地图。"
seo_title: "useMapbox"
seo_description: "Look up a mounted map context by id from the registry to access the map outside its component tree or across routes."
canonical_url: "https://mapbox.mhaibaraai.cn/docs/composables/use-mapbox"
---
# useMapbox

> 按 id 从注册表获取已挂载地图的上下文，在组件树之外或跨路由访问地图。

## 简介

`useMapbox` 是 [useMap](/docs/composables/use-map) 的「逃生口」：按 id 从注册表获取已挂载地图的上下文，可在 `<MapboxMap>` 组件树之外、甚至跨路由访问地图。未找到对应 id 时返回 `undefined`。

> \[\!NOTE\]
> 
> 仅对显式设置了 
> 
> map-id
> 
>  的 
> 
> <MapboxMap>
> 
>  生效（未指定 id 的地图不进注册表）。注册发生在地图挂载阶段，故调用时机需在地图挂载之后；常见做法是在事件回调或 
> 
> whenLoaded()
> 
>  中使用。

## 用法

工具栏位于 `<MapboxMap>` 子树之外，经 `useMapbox(id)` 跨树访问地图并飞行到目标城市：

```vue [UseMapboxExample.vue]
<script setup lang="ts">
const mapId = 'use-mapbox-demo'

const cities: Record<string, [number, number]> = {
  北京: [116.39, 39.91],
  上海: [121.47, 31.23],
  广州: [113.26, 23.13]
}

// 按钮位于 <MapboxMap> 子树之外，经 useMapbox(id) 逃生口跨树访问已挂载的地图
function flyTo(center: [number, number]) {
  useMapbox(mapId)?.whenLoaded().then(map => map.flyTo({ center, zoom: 10 }))
}
</script>

<template>
  <div class="relative h-115 w-full overflow-hidden rounded-(--ui-radius) border border-default">
    <MapboxMap :map-id="mapId" :options="{ style: 'mapbox://styles/mapbox/light-v11', center: [116.39, 39.91], zoom: 9 }" />
    <div class="absolute left-2 top-2 z-10 flex gap-1">
      <UButton v-for="(center, name) in cities" :key="name" size="sm" @click="flyTo(center)">
        {{ name }}
      </UButton>
    </div>
  </div>
</template>
```

## API

### `useMapbox()`

按 id 从注册表获取地图上下文。

**id** (`string`) *required*: 目标地图的 map-id。

返回 `MapboxContext | undefined`：对应 id 的地图上下文（结构见 [useMap](/docs/composables/use-map#api)），未找到时为 `undefined`。

## Changelog

See commit history for [src/runtime/composables/useMapbox.ts](https://github.com/mhaibaraai/movk-mapbox/commits/main/src/runtime/composables/useMapbox.ts).


## Sitemap

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