---
title: "useMapbox"
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/en/docs/composables/use-mapbox"
---
# useMapbox

> Look up a mounted map context by id from the registry to access the map outside its component tree or across routes.

## Introduction

`useMapbox` is the escape hatch for [useMap](https://mapbox.mhaibaraai.cn/docs/composables/use-map): it looks up a mounted map context by id from the registry, allowing access to the map outside the `<MapboxMap>` component tree or even across routes. Returns `undefined` when no matching id is found.

> [!NOTE]
> 
> Only works with 
> 
> <MapboxMap>
> 
>  instances that have an explicit 
> 
> map-id
> 
>  set (maps without an id are not registered). Registration happens at mount time, so this composable must be called after the map has mounted — a common pattern is to use it inside an event callback or within 
> 
> whenLoaded()
> 
> .

## Usage

A toolbar located outside the `<MapboxMap>` subtree accesses the map via `useMapbox(id)` and flies to a target city:

```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()`

Looks up a map context by id from the registry.

**id** (`string`) *required*: The map-id of the target map.

Returns `MapboxContext | undefined`: the context for the matching id (see [useMap](https://mapbox.mhaibaraai.cn/docs/composables/use-map#api) for the shape), or `undefined` if not found.

## 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](https://mapbox.mhaibaraai.cn/sitemap.md) for all pages.
