---
title: "useMapAnimation"
description: "地图帧动画原语，基于 requestAnimationFrame，仅在地图存在且样式就绪时调用回调。"
seo_title: "useMapAnimation"
seo_description: "Map frame-animation primitive built on requestAnimationFrame; invokes the frame callback only when the map exists and the style is loaded."
canonical_url: "https://mapbox.mhaibaraai.cn/docs/composables/use-map-animation"
---
# useMapAnimation

> 地图帧动画原语，基于 requestAnimationFrame，仅在地图存在且样式就绪时调用回调。

## 简介

`useMapAnimation` 是地图帧动画原语：基于 `useRafFn`（组件卸载自动停止），仅在地图存在且样式就绪时调用 `frame` 回调，回调第二参为自启动起的累计毫秒数。动效组件与帧驱动图片均复用它。返回 `pause` / `resume` / `isActive` 控制运行状态。

> \[\!NOTE\]
> 
> 在 
> 
> <MapboxMap>
> 
>  子树外使用时经 
> 
> options.mapId
> 
>  指定目标地图。回调内每帧执行，避免在其中创建新对象或做重计算。

## 用法

每帧驱动 `circle-radius` 周期脉动：

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

const mapId = 'use-map-animation-demo'

const data: FeatureCollection = {
  type: 'FeatureCollection',
  features: [
    { type: 'Feature', properties: {}, geometry: { type: 'Point', coordinates: [116.397, 39.908] } }
  ]
}

// 每帧驱动 circle-radius 周期脉动；图层未就绪时跳过
useMapAnimation((map, elapsed) => {
  if (!map.getLayer('pulse')) return
  map.setPaintProperty('pulse', 'circle-radius', 14 + 8 * Math.sin(elapsed / 400))
}, { mapId })
</script>

<template>
  <div class="h-115 w-full overflow-hidden rounded-(--ui-radius) border border-default">
    <MapboxMap :map-id="mapId" :options="{ style: 'mapbox://styles/mapbox/dark-v11', center: [116.397, 39.908], zoom: 12 }">
      <MapboxLayer
        layer-id="pulse"
        type="circle"
        :source="{ type: 'geojson', data }"
        :paint="{ 'circle-color': '#22d3ee', 'circle-opacity': 0.6, 'circle-radius': 14 }"
      />
    </MapboxMap>
  </div>
</template>
```

## API

### `useMapAnimation()`

创建帧动画循环。

**frame** (`(map: Map, elapsedMs: number) => void`) *required*: 每帧回调；elapsedMs 为自启动起的累计毫秒数。

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

**options.immediate** (`boolean`): 创建后立即启动，默认 true。

返回 `UseMapAnimationReturn`：

**pause** (`() => void`): 暂停动画。

**resume** (`() => void`): 恢复动画。

**isActive** (`Readonly<Ref<boolean>>`): 是否正在运行。

## Changelog

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


## Sitemap

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