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.
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.
<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>
Executes a callback function when the Mapbox map is available.
| Prop | Default | Type |
|---|---|---|
callback* | MapboxCallbackThe callback function to execute when the map is available |
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
<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>
<script setup lang="ts">
useMapboxBeforeLoad((map) => {
// Add custom controls to the map
const control = new CustomControl();
map.addControl(control, 'top-right');
// Set up control event listeners
control.on('click', () => {
// Handle control click
});
});
</script>