---
title: "useMaplibreCamera"
description: "相机操作助手，封装 flyTo / easeTo / jumpTo / fitBounds，自动等待地图加载完成。"
canonical_url: "https://maplibre.mhaibaraai.cn/docs/composables/use-maplibre-camera"
---
# useMaplibreCamera

> 相机操作助手，封装 flyTo / easeTo / jumpTo / fitBounds，自动等待地图加载完成。

## 简介

`useMaplibreCamera` 封装常用相机操作：平滑飞行、缓动、立即跳转与缩放到范围。所有方法均返回 `Promise`，内部等待地图加载完成后执行，无需手动判断就绪状态。`fitBounds` 额外接受任意 GeoJSON，自动求其包围盒。

> [!NOTE]
> 
> 在 
> 
> <MaplibreMap>
> 
>  子树外使用时，经 
> 
> options.mapId
> 
>  指定目标地图。

## 用法

工具栏触发飞行与缩放到路线（`fitBounds` 直接传入 GeoJSON）：

```vue [UseMaplibreCameraExample.vue]
<script setup lang="ts">
import type { FeatureCollection } from 'geojson'

const mapId = 'use-maplibre-camera-demo'

const route: FeatureCollection = {
  type: 'FeatureCollection',
  features: [
    {
      type: 'Feature',
      properties: {},
      geometry: {
        type: 'LineString',
        coordinates: [
          [116.39, 39.91],
          [117.20, 39.13],
          [118.18, 39.63],
          [119.60, 39.94]
        ]
      }
    }
  ]
}

const { flyTo, fitBounds } = useMaplibreCamera({ mapId })
</script>

<template>
  <div class="relative h-115 w-full overflow-hidden rounded-(--ui-radius) border border-default">
    <MaplibreMap :map-id="mapId" :options="{ style: 'https://tiles.openfreemap.org/styles/positron', center: [117.5, 39.6], zoom: 6 }">
      <MaplibreLayer
        layer-id="route"
        type="line"
        :source="{ type: 'geojson', data: route }"
        :layout="{ 'line-cap': 'round', 'line-join': 'round' }"
        :paint="{ 'line-color': '#8b5cf6', 'line-width': 4 }"
      />
    </MaplibreMap>
    <div class="absolute left-2 top-2 z-10 flex gap-1">
      <UButton size="sm" @click="fitBounds(route, { padding: 60 })">
        缩放到路线
      </UButton>
      <UButton size="sm" variant="soft" @click="flyTo({ center: [116.39, 39.91], zoom: 11, pitch: 45 })">
        飞向北京
      </UButton>
    </div>
  </div>
</template>
```

## API

### `useMaplibreCamera()`

创建相机操作助手。

**options.mapId** (`string`): 目标地图 id；在 <MaplibreMap> 子树外使用时必填。

返回 `UseMaplibreCameraReturn`：

**flyTo** (`(options: EasingOptions) => Promise<void>`): 平滑飞行到目标视角。

**easeTo** (`(options: EasingOptions) => Promise<void>`): 缓动到目标视角。

**jumpTo** (`(options: CameraOptions) => Promise<void>`): 立即跳转到目标视角。

**fitBounds** (`(target: LngLatBoundsLike | GeoJSON, options?: FitBoundsOptions) => Promise<void>`): 缩放到目标范围；target 支持包围盒或任意 GeoJSON（自动求包围盒）。

## Changelog

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


## Sitemap

See the full [sitemap](https://maplibre.mhaibaraai.cn/sitemap.md) for all pages.
