---
title: "defineMapboxControl"
description: "Quickly define a custom Mapbox IControl with callback-style onAdd and onRemove instead of writing a control class."
canonical_url: "https://mapbox.mhaibaraai.cn/en/docs/composables/define-mapbox-control"
---
# defineMapboxControl

> Quickly define a custom Mapbox IControl with callback-style onAdd and onRemove instead of writing a control class.

## Introduction

`defineMapboxControl` uses callback-style `onAdd` and `onRemove` handlers to quickly define a custom control that conforms to the `IControl` interface, eliminating the boilerplate of writing a control class. `onAdd` returns the control's DOM element; `onRemove` handles cleanup. The returned object can be passed directly to `map.addControl`.

> [!NOTE]
> 
> This helper only produces a control object — it does not mount it. Obtain the map instance via 
> 
> useMap
> 
>  or 
> 
> useMapbox
> 
>  and then call 
> 
> addControl
> 
> .

## Usage

Define a "back to origin" button control and add it to the map:

```vue [DefineMapboxControlExample.vue]
<script setup lang="ts">
const mapId = 'define-mapbox-control-demo'
const home: [number, number] = [116.397, 39.908]

// 回调式定义控件：onAdd 返回 DOM 元素，点击回到原点
const control = defineMapboxControl(
  (map) => {
    const group = document.createElement('div')
    group.className = 'mapboxgl-ctrl mapboxgl-ctrl-group'
    const button = document.createElement('button')
    button.type = 'button'
    button.title = '回到原点'
    button.textContent = '⌖'
    button.addEventListener('click', () => map.flyTo({ center: home, zoom: 11 }))
    group.appendChild(button)
    return group
  },
  () => {}
)

onMounted(() => {
  useMapbox(mapId)?.whenLoaded().then(map => map.addControl(control, 'top-right'))
})
</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/light-v11', center: home, zoom: 11 }" />
  </div>
</template>
```

## API

### `defineMapboxControl()`

Creates a custom control object.

**onAdd** (`(map: Map) => HTMLElement`) *required*: Called when the control is added to the map; returns the control's DOM element.

**onRemove** (`(map: Map) => void`) *required*: Called when the control is removed from the map; responsible for cleanup.

Returns `IControl`: a control object ready to pass to `map.addControl`.

## Changelog

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


## Sitemap

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