Skip to content

Composables API Reference

Vue3 MapLibre GL provides a comprehensive set of composables for building interactive maps with Vue 3 Composition API. All composables are designed with TypeScript support, reactive data binding, and comprehensive error handling.

Map Composables

useCreateMaplibre

The core composable for creating and managing MapLibre GL Maps with enhanced error handling and reactive state management.

Parameters

ParameterTypeDescription
elRefMaybeRef<HTMLElement | undefined>Reference to the HTML element container
styleRefMaybeRef<StyleSpecification | string>Reference to the map style
propsCreateMaplibrePropsConfiguration options for the map

CreateMaplibreProps Interface

PropertyTypeDefaultDescription
register(actions: EnhancedCreateMaplibreActions) => voidundefinedCallback for registering map actions
debugbooleanfalseEnable debug logging
onLoad(map: Map) => voidundefinedLoad success callback
onError(error: any) => voidundefinedError handling callback

Returns

PropertyTypeDescription
mapInstanceComputedRef<Map | null>Reactive map instance
setCenter(center: LngLatLike) => voidSet map center coordinates
setBearing(bearing: number) => voidSet map bearing (rotation)
setZoom(zoom: number) => voidSet map zoom level
setPitch(pitch: number) => voidSet map pitch (tilt)
setStyle(style: StyleSpecification | string) => voidSet map style
setMaxBounds(bounds: LngLatBoundsLike) => voidSet maximum bounds
setMaxPitch(pitch: number) => voidSet maximum pitch
setMaxZoom(zoom: number) => voidSet maximum zoom
setMinPitch(pitch: number) => voidSet minimum pitch
setMinZoom(zoom: number) => voidSet minimum zoom
setRenderWorldCopies(render: boolean) => voidSet world copies rendering
isMapReadyComputedRef<boolean>Whether the map is ready
isMapLoadingComputedRef<boolean>Whether the map is loading
hasMapErrorComputedRef<boolean>Whether the map has an error
refreshMap() => voidRefresh the map instance
destroyMap() => voidDestroy the map instance

Example

typescript
import { ref } from 'vue';
import { useCreateMaplibre } from 'vue3-maplibre-gl';

const mapContainer = ref<HTMLElement>();
const mapStyle = ref('https://demotiles.maplibre.org/style.json');

const { mapInstance, setCenter, setZoom, isMapReady, isMapLoading } =
  useCreateMaplibre(mapContainer, mapStyle, {
    debug: true,
    onLoad: (map) => {
      console.log('Map loaded:', map);
    },
    onError: (error) => {
      console.error('Map error:', error);
    },
  });

// Use the map instance
watch(isMapReady, (ready) => {
  if (ready) {
    setCenter([0, 0]);
    setZoom(10);
  }
});

useMaplibre

A simplified composable for basic map operations and state management.

Parameters

ParameterTypeDescription
propsUseMaplibrePropsConfiguration options

Returns

PropertyTypeDescription
mapInstanceComputedRef<Map | null>Reactive map instance
isReadyComputedRef<boolean>Whether the map is ready

Example

typescript
import { useMaplibre } from 'vue3-maplibre-gl';

const { mapInstance, isReady } = useMaplibre({
  debug: true,
});

Layer Composables

useCreateFillLayer

Creates and manages MapLibre GL Fill Layers with reactive updates and comprehensive event handling.

Parameters

ParameterTypeDescription
propsCreateFillLayerPropsFill layer configuration

CreateFillLayerProps Interface

PropertyTypeDescription
mapMaybeRef<Map | null>Map instance reference
sourceMaybeRef<string | object>Data source for the layer
styleFillLayerStyleFill layer style configuration
filterFilterSpecificationFilter expression
idstringLayer identifier
maxzoomnumberMaximum zoom level
minzoomnumberMinimum zoom level
metadataobjectLayer metadata
sourceLayerstringSource layer name
register(actions: CreateLayerActions, map: Map) => voidRegistration callback

Returns

PropertyTypeDescription
getLayerComputedRef<LayerSpecification | null>Get layer specification
setBeforeId(beforeId?: string) => voidSet layer insertion point
setFilter(filter?: FilterSpecification) => voidSet layer filter
setStyle(style: FillLayerStyle) => voidSet layer style
setZoomRange(min: number, max: number) => voidSet zoom range
setLayoutProperty(name: string, value: any) => voidSet layout property

Example

typescript
import { ref } from 'vue';
import { useCreateFillLayer } from 'vue3-maplibre-gl';

const mapInstance = ref<Map | null>(null);
const sourceRef = ref('my-source');

const { getLayer, setStyle, setFilter } = useCreateFillLayer({
  map: mapInstance,
  source: sourceRef,
  id: 'fill-layer',
  style: {
    'fill-color': '#088',
    'fill-opacity': 0.8,
  },
  filter: ['==', 'type', 'polygon'],
  register: (actions, map) => {
    console.log('Fill layer registered:', actions);
  },
});

// Update layer style
setStyle({
  'fill-color': '#ff0000',
  'fill-opacity': 0.6,
});

// Update layer filter
setFilter(['==', 'category', 'important']);

useCreateCircleLayer

Creates and manages MapLibre GL Circle Layers for point data visualization.

Parameters

Similar to useCreateFillLayer but with CircleLayerStyle for styling.

Example

typescript
import { useCreateCircleLayer } from 'vue3-maplibre-gl';

const { getLayer, setStyle } = useCreateCircleLayer({
  map: mapInstance,
  source: sourceRef,
  id: 'circle-layer',
  style: {
    'circle-radius': 6,
    'circle-color': '#007cbf',
    'circle-stroke-width': 2,
    'circle-stroke-color': '#fff',
  },
});

useCreateLineLayer

Creates and manages MapLibre GL Line Layers for linear features.

Parameters

Similar to useCreateFillLayer but with LineLayerStyle for styling.

Example

typescript
import { useCreateLineLayer } from 'vue3-maplibre-gl';

const { getLayer, setStyle } = useCreateLineLayer({
  map: mapInstance,
  source: sourceRef,
  id: 'line-layer',
  style: {
    'line-color': '#007cbf',
    'line-width': 3,
    'line-opacity': 0.8,
  },
});

useCreateSymbolLayer

Creates and manages MapLibre GL Symbol Layers for icons and text.

Parameters

Similar to useCreateFillLayer but with SymbolLayerStyle for styling.

Example

typescript
import { useCreateSymbolLayer } from 'vue3-maplibre-gl';

const { getLayer, setStyle } = useCreateSymbolLayer({
  map: mapInstance,
  source: sourceRef,
  id: 'symbol-layer',
  style: {
    'text-field': ['get', 'name'],
    'text-font': ['Open Sans Regular'],
    'text-size': 12,
    'text-color': '#333',
  },
});

Source Composables

useCreateGeoJsonSource

Creates and manages MapLibre GL GeoJSON Sources with reactive data updates and comprehensive error handling.

Parameters

ParameterTypeDescription
propsCreateGeoJsonSourcePropsGeoJSON source configuration

CreateGeoJsonSourceProps Interface

PropertyTypeDescription
mapMaybeRef<Map | null>Map instance reference
idstringSource identifier
dataGeoJSONSourceSpecification['data']GeoJSON data
optionsPartial<GeoJSONSourceSpecification>Additional source options
debugbooleanEnable debug logging
register(actions: CreateGeoJsonSourceActions, map: Map) => voidRegistration callback

Returns

PropertyTypeDescription
sourceIdstringSource identifier
getSourceShallowRef<GeoJSONSource | null>Get source instance
setData(data: GeoJSONSourceSpecification['data']) => voidUpdate source data
removeSource() => voidRemove source from map
refreshSource() => voidRefresh source
sourceStatusReadonly<SourceStatus>Source status
isSourceReadybooleanWhether source is ready

Example

typescript
import { ref } from 'vue';
import { useCreateGeoJsonSource } from 'vue3-maplibre-gl';

const mapInstance = ref<Map | null>(null);
const geoJsonData = ref({
  type: 'FeatureCollection',
  features: [],
});

const { sourceId, getSource, setData, isSourceReady } = useCreateGeoJsonSource({
  map: mapInstance,
  id: 'my-geojson-source',
  data: geoJsonData.value,
  options: {
    cluster: true,
    clusterMaxZoom: 14,
    clusterRadius: 50,
  },
  debug: true,
  register: (actions, map) => {
    console.log('GeoJSON source registered:', actions);
  },
});

// Update source data
const newData = {
  type: 'FeatureCollection',
  features: [
    {
      type: 'Feature',
      geometry: {
        type: 'Point',
        coordinates: [0, 0],
      },
      properties: {
        name: 'Sample Point',
      },
    },
  ],
};

setData(newData);

useGeoJsonSource

A simplified composable for managing GeoJSON source instances with enhanced error handling.

Parameters

ParameterTypeDescription
propsUseGeoJsonSourcePropsConfiguration options

Returns

PropertyTypeDescription
sourceIdComputedRef<string | undefined>Source identifier
getSourceComputedRef<GeoJSONSource | null>Get source instance
setData(data: GeoJSONSourceSpecification['data']) => voidUpdate source data
refreshSource() => voidRefresh source
isSourceReadyComputedRef<boolean>Whether source is ready
sourceStatusComputedRef<GeoJsonSourceStatus>Source status

Example

typescript
import { useGeoJsonSource } from 'vue3-maplibre-gl';

const { sourceId, getSource, setData, isSourceReady, register } =
  useGeoJsonSource({
    debug: true,
    autoRefresh: true,
  });

// Register with a source instance
register(sourceActions);

Control Composables

useGeolocateControl

Creates and manages MapLibre GL Geolocate Controls with comprehensive event handling.

Parameters

ParameterTypeDescription
propsUseGeolocateControlPropsGeolocate control configuration

UseGeolocateControlProps Interface

PropertyTypeDescription
mapMaybeRef<Map | null>Map instance reference
positionControlPositionControl position on map
optionsGeolocateControlOptionsControl options
debugbooleanEnable debug logging

Returns

PropertyTypeDescription
controlShallowRef<GeolocateControl | null>Control instance
trigger() => booleanTrigger geolocation
isActiveComputedRef<boolean>Whether control is active
isSupportedComputedRef<boolean>Whether geolocation is supported

Example

typescript
import { ref } from 'vue';
import { useGeolocateControl } from 'vue3-maplibre-gl';

const mapInstance = ref<Map | null>(null);

const { control, trigger, isActive, isSupported } = useGeolocateControl({
  map: mapInstance,
  position: 'top-right',
  options: {
    positionOptions: {
      enableHighAccuracy: true,
    },
    trackUserLocation: true,
    showUserHeading: true,
  },
  debug: true,
});

// Manually trigger geolocation
if (isSupported.value) {
  trigger();
}

Event Composables

useMapEventListener

Provides reactive event handling for MapLibre GL map events with automatic cleanup.

Parameters

ParameterTypeDescription
propsUseMapEventListenerPropsEvent listener configuration

UseMapEventListenerProps Interface

PropertyTypeDescription
mapMaybeRef<Map | null>Map instance reference
eventMapEventTypeEvent type to listen for
handler(event: any) => voidEvent handler function
optionsAddEventListenerOptionsEvent listener options

Example

typescript
import { ref } from 'vue';
import { useMapEventListener } from 'vue3-maplibre-gl';

const mapInstance = ref<Map | null>(null);

// Listen for map click events
useMapEventListener({
  map: mapInstance,
  event: 'click',
  handler: (event) => {
    console.log('Map clicked at:', event.lngLat);
  },
});

// Listen for map zoom events
useMapEventListener({
  map: mapInstance,
  event: 'zoom',
  handler: (event) => {
    console.log('Map zoom level:', event.target.getZoom());
  },
});

useLayerEventListener

Provides reactive event handling for MapLibre GL layer events with automatic cleanup.

Parameters

ParameterTypeDescription
propsUseLayerEventListenerPropsLayer event listener configuration

UseLayerEventListenerProps Interface

PropertyTypeDescription
mapMaybeRef<Map | null>Map instance reference
layerIdstringLayer identifier
eventMapLayerEventTypeEvent type to listen for
handler(event: any) => voidEvent handler function

Example

typescript
import { ref } from 'vue';
import { useLayerEventListener } from 'vue3-maplibre-gl';

const mapInstance = ref<Map | null>(null);

// Listen for layer click events
useLayerEventListener({
  map: mapInstance,
  layerId: 'my-layer',
  event: 'click',
  handler: (event) => {
    console.log('Layer clicked:', event.features[0]);
  },
});

// Listen for layer hover events
useLayerEventListener({
  map: mapInstance,
  layerId: 'my-layer',
  event: 'mouseenter',
  handler: (event) => {
    console.log('Mouse entered layer:', event.features[0]);
  },
});

Utility Composables

useFlyTo

Provides smooth animated transitions to new map positions with customizable easing and duration.

Parameters

ParameterTypeDescription
propsUseFlyToPropsFly-to animation configuration

UseFlyToProps Interface

PropertyTypeDescription
mapMaybeRef<Map | null>Map instance reference
optionsFlyToOptionsAnimation options

Returns

PropertyTypeDescription
flyTo(options: FlyToOptions) => voidExecute fly-to animation
isFlyingComputedRef<boolean>Whether animation is active

Example

typescript
import { ref } from 'vue';
import { useFlyTo } from 'vue3-maplibre-gl';

const mapInstance = ref<Map | null>(null);

const { flyTo, isFlying } = useFlyTo({
  map: mapInstance,
});

// Fly to a new location
flyTo({
  center: [0, 0],
  zoom: 10,
  duration: 2000,
  essential: true,
});

// Check if animation is active
watch(isFlying, (flying) => {
  console.log('Animation active:', flying);
});

useEaseTo

Provides smooth animated transitions with easing functions for map camera changes.

Parameters

ParameterTypeDescription
propsUseEaseToPropsEase-to animation configuration

Returns

PropertyTypeDescription
easeTo(options: EaseToOptions) => voidExecute ease-to animation
isEasingComputedRef<boolean>Whether animation is active

Example

typescript
import { useEaseTo } from 'vue3-maplibre-gl';

const { easeTo, isEasing } = useEaseTo({
  map: mapInstance,
});

// Ease to a new position
easeTo({
  center: [0, 0],
  zoom: 12,
  bearing: 45,
  pitch: 30,
  duration: 1000,
});

useJumpTo

Provides instant map position changes without animation.

Parameters

ParameterTypeDescription
propsUseJumpToPropsJump-to configuration

Returns

PropertyTypeDescription
jumpTo(options: CameraOptions) => voidExecute instant position change

Example

typescript
import { useJumpTo } from 'vue3-maplibre-gl';

const { jumpTo } = useJumpTo({
  map: mapInstance,
});

// Jump to a new position instantly
jumpTo({
  center: [0, 0],
  zoom: 15,
  bearing: 0,
  pitch: 0,
});

useBounds

Provides utilities for working with map bounds and fitting content to view.

Parameters

ParameterTypeDescription
propsUseBoundsPropsBounds configuration

Returns

PropertyTypeDescription
fitBounds(bounds: LngLatBoundsLike, options?: FitBoundsOptions) => voidFit map to bounds
getBounds() => LngLatBoundsGet current map bounds
setBounds(bounds: LngLatBoundsLike) => voidSet map bounds

Example

typescript
import { useBounds } from 'vue3-maplibre-gl';

const { fitBounds, getBounds, setBounds } = useBounds({
  map: mapInstance,
});

// Fit map to specific bounds
fitBounds(
  [
    [-74.0, 40.7], // Southwest coordinates
    [-73.9, 40.8], // Northeast coordinates
  ],
  {
    padding: 20,
    duration: 1000,
  },
);

// Get current bounds
const currentBounds = getBounds();
console.log('Current bounds:', currentBounds);

useZoom

Provides utilities for managing map zoom levels with smooth animations.

Parameters

ParameterTypeDescription
propsUseZoomPropsZoom configuration

Returns

PropertyTypeDescription
zoomIn(options?: ZoomOptions) => voidZoom in by one level
zoomOut(options?: ZoomOptions) => voidZoom out by one level
zoomTo(zoom: number, options?: ZoomOptions) => voidZoom to specific level
getZoom() => numberGet current zoom level

Example

typescript
import { useZoom } from 'vue3-maplibre-gl';

const { zoomIn, zoomOut, zoomTo, getZoom } = useZoom({
  map: mapInstance,
});

// Zoom in
zoomIn({ duration: 500 });

// Zoom out
zoomOut({ duration: 500 });

// Zoom to specific level
zoomTo(12, { duration: 1000 });

// Get current zoom
const currentZoom = getZoom();
console.log('Current zoom:', currentZoom);

useLogger

Provides consistent logging functionality with debug level control.

Parameters

ParameterTypeDescription
debugbooleanWhether to enable debug logging

Returns

PropertyTypeDescription
log(message: string, ...args: any[]) => voidLog debug message
logError(message: string, ...args: any[]) => voidLog error message
logWarn(message: string, ...args: any[]) => voidLog warning message

Example

typescript
import { useLogger } from 'vue3-maplibre-gl';

const { log, logError, logWarn } = useLogger(true);

// Log debug information
log('Map initialized successfully');

// Log errors
logError('Failed to load map style:', error);

// Log warnings
logWarn('Deprecated API usage detected');

Released under the MIT License.