Accessing The Map

Events

All Map events are accessible directly through the component (With full Typescript support!)

View a list of events in the Mapbox Docs

Example:

    <MapboxMap
      ...
      @load="exampleFunction"
      @click="exampleFunction"
      @resize="exampleFunction"
    >

You can access events directly on layers as well

Example:

    <MapboxLayer
      ...
      @click="exampleFunction"
    >

Composables

useMapbox

The simplest way to access the map instance on setup is with the useMapbox composable. You must provide the map id.

The map instance will not be available until the page is fully loaded, so you must access it through a callback.

<script setup>
    useMapbox(mapId, (map) => {
      // Do whatever with map here
    })
</script>
NOTE: The callback will only be run after the map has loaded (so if you do map.on('load') inside useMapbox, it will not work).

If you want to access the map before it has loaded, there is the useMapboxBeforeLoad composable instead.

useMapbox should be preferred over useMapboxBeforeLoad with map.on('load') to ensure that your code gets run on reactive updates while the map is already loaded.


Refs

When working with the map reactively (for example, in a watcher or computed method), you should instead use the map ref. The refs should be treated similar to Vue template refs.

It is important to remember that the refs will be undefined until they have been initialized, which will be after the component is mounted.
  const mapRef = useMapboxRef(mapId);

  const mapStyle = computed(() => {
    return mapRef.value?.getStyle();
  });

  watch([lng, lat], () => {
    mapRef.value?.flyTo({
        center: [lng.value, lat.value],
        zoom: 16,
        speed: 4,
    });
  });