---
title: "useMap"
description: "注入当前 MapboxMap 上下文，在子组件中直接访问地图实例与就绪状态。"
seo_title: "useMap"
seo_description: "Inject the current MapboxMap context to access the map instance, loading state and the onReady hook from any descendant component."
canonical_url: "https://mapbox.mhaibaraai.cn/docs/composables/use-map"
---
# useMap

> 注入当前 MapboxMap 上下文，在子组件中直接访问地图实例与就绪状态。

## 简介

`useMap` 注入由最近的 `<MapboxMap>` 下发的上下文，返回地图实例引用、样式就绪状态与就绪回调。它是所有声明式子组件读取地图的统一入口，无需经 id 查表。

> \[\!NOTE\]
> 
> 必须在 
> 
> <MapboxMap>
> 
>  子树内调用，否则抛错。需要在地图组件树之外访问，请改用 
> 
> useMapbox
> 
> 。

`onReady` 在样式首次加载与每次 `setStyle` 后都会重跑，是建 source / layer、绑定事件的推荐入口；`map` 在 SSR 与挂载前为 `undefined`，组件已做 SSR 安全处理。

## 用法

子组件经 `useMap()` 读取实时相机状态（中心、缩放、就绪状态）：

```vue [UseMapExample.vue]
<script setup lang="ts">
import { defineComponent, h, ref } from 'vue'

// 子组件位于 <MapboxMap> 子树内，经 useMap() 注入上下文读取实时相机状态
const MapStatus = defineComponent({
  name: 'MapStatus',
  setup() {
    const { isLoaded, onReady } = useMap()
    const center = ref('')
    const zoom = ref(0)

    onReady((map) => {
      const sync = () => {
        const c = map.getCenter()
        center.value = `${c.lng.toFixed(3)}, ${c.lat.toFixed(3)}`
        zoom.value = Number(map.getZoom().toFixed(2))
      }
      sync()
      map.on('move', sync)
    })

    return () => h('div', { class: 'absolute left-2 top-2 z-10 space-y-0.5 rounded bg-default/90 px-3 py-2 text-xs text-default ring ring-default' }, [
      h('div', `样式就绪：${isLoaded.value ? '是' : '否'}`),
      h('div', `中心：${center.value}`),
      h('div', `缩放：${zoom.value}`)
    ])
  }
})
</script>

<template>
  <div class="h-115 w-full overflow-hidden rounded-(--ui-radius) border border-default">
    <MapboxMap :options="{ style: 'mapbox://styles/mapbox/light-v11', center: [116.397, 39.908], zoom: 10 }">
      <MapStatus />
    </MapboxMap>
  </div>
</template>
```

## API

### `useMap()`

注入当前地图上下文，返回 `MapboxContext`。无参数。

返回 `MapboxContext`：

**id** (`string`): 地图 id，未显式指定时为内部生成的唯一值。

**map** (`ShallowRef<Map | undefined>`): 地图实例引用；SSR 与挂载前为 undefined。

**isLoaded** (`Ref<boolean>`): 样式是否已加载完成。

**whenLoaded** (`() => Promise<Map>`): 样式首次加载完成时 resolve，返回地图实例。

**onReady** (`(cb: (map: Map) => void) => () => void`): 样式就绪即执行回调，且每次 setStyle 重新加载后重跑（用于重建 source / layer）；返回取消订阅函数。

## Changelog

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


## Sitemap

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