useMapboxBeforeLoad

Gitlab
A composable that executes a callback function when the Mapbox map is available.
Added since: v0.1.0
Last changed:

Overview

useMapboxBeforeLoad() is a composable that helps you interact with the Mapbox map in a smart way. It takes care of executing your code at just the right time - whether the map is already loaded or still in the process of loading. This makes it perfect for setting up your map configurations and event listeners without worrying about timing issues.

Usage

The composable is particularly useful when you need to interact with the map from child components or when you want to ensure map operations only happen after the map is fully loaded.

MapChildComponent.vue
<script setup lang="ts">
const { map } = injectMapboxMapContext();
const events = ref(["resize", "remove", "load", "render", "idle", "error"])

useMapboxBeforeLoad((map) => {
    events.value.forEach((eventName) => {
        map?.on(eventName, (e) => {
            emit(eventName, e);
        })
    })
});
</script>

API Reference

useMapboxBeforeLoad()

Executes a callback function when the Mapbox map is available.

PropDefaultType
callback*
MapboxCallback
The callback function to execute when the map is available

Type Definitions

export type MapboxCallback = (map: Map) => void;

/**
 * A composable that executes a callback function when the Mapbox map is available.
 * If the map is already loaded, the callback is executed immediately.
 * Otherwise, it waits for the map to be loaded before executing the callback.
 *
 * @param callback - A function that will be called with the Mapbox map instance once it's available.
 */
export function useMapboxBeforeLoad(callback: MapboxCallback): void

Example

<script setup lang="ts">
useMapboxBeforeLoad((map) => {
  // Add a listener for the 'load' event
  map.on('load', 'mapId', (e) => emit('loaded', e));
  
  // Set initial map properties
  map.setZoom(12);
  map.setCenter([-74.5, 40]);
});
</script>

Changelog

v0.2.0

on

#bda27275

-

feat: documented useMapboxBeforeLoad and exported related types