Advanced
Access the underlying MapLibre GL instance for advanced customization.
Access the underlying MapLibre GL map instance to use any feature from the MapLibre GL JS API.
You can use getContext in child components to access the map instance.
Using Context
For child components rendered inside Map, use getContext("map") to access the map instance and listen to events.
Listening to Map Events
Use onMount with getContext to set up event listeners
in child components.
<script lang="ts">
import { Map } from "$lib/components/ui/map";
import MapLibreGL from "maplibre-gl";
import { getContext } from "svelte";
import { onMount } from "svelte";
// For child components inside Map, use getContext
function MapEventListener() {
const mapCtx = getContext<{
getMap: () => MapLibreGL.Map | null;
isLoaded: () => boolean;
}>("map");
onMount(() => {
const map = mapCtx.getMap();
if (!map || !mapCtx.isLoaded()) return;
const handleClick = (e: MapLibreGL.MapMouseEvent) => {
console.log("Clicked at:", e.lngLat);
};
map.on("click", handleClick);
return () => map.off("click", handleClick);
});
return null;
}
</script>
// Usage
<Map center={[-74, 40.7]} zoom={10}>
<MapEventListener />
</Map>Example: Custom Controls
This example shows how to create custom controls that manipulate the map's pitch and bearing, and listen to map events to display real-time values.
Example: Custom GeoJSON Layer
Add custom GeoJSON data as layers with fill and outline styles. This example shows NYC parks with hover interactions.
Example: Markers via Layers
When displaying hundreds or thousands of markers, use GeoJSON layers instead of DOM-based MapMarker components. This approach renders markers on the WebGL canvas, providing
significantly better performance.
Extend to Build
You can extend this to build custom features like:
- Real-time tracking - Live location updates for delivery, rides, or fleet management
- Geofencing - Trigger actions when users enter or leave specific areas
- Heatmaps - Visualize density data like population, crime, or activity hotspots
- Drawing tools - Let users draw polygons, lines, or place markers for custom areas
- 3D buildings - Extrude building footprints for urban visualization
- Animations - Animate markers along routes or create fly-through experiences
- Custom data layers - Overlay weather, traffic, or satellite imagery