Map Events and Basic Controls

Listen for map loading, mouse, and camera events, and add navigation, scale, geolocation, and popups.

🎯 Introduction

By the end of this article, you will be able to work with the map at the right time, read coordinates from mouse events, and add common controls and popups.


🧱 Loading events determine when resources are ready

map.on('load', () => {
    // The initial style has loaded; application sources and layers can now be added
})

map.on('idle', () => {
    // Resources for the current viewport have loaded and no camera transition is running
})

Use load to add sources and layers initially. idle can fire repeatedly and is useful for waiting until the current view settles; do not put one-time initialization directly in it.


🖱 Mouse and camera events

function handleMapClick(event: mapboxgl.MapMouseEvent) {
    console.log(event.lngLat.lng, event.lngLat.lat)
}

map.on('click', handleMapClick)
map.on('dblclick', event => console.log(event.lngLat))
map.on('mousemove', event => console.log(event.point))

map.on('move', () => console.log(map.getCenter()))
map.on('moveend', () => console.log('Camera movement ended'))
map.on('zoom', () => console.log(map.getZoom()))
map.on('zoomend', () => console.log('Zoom ended'))

event.lngLat gives the geographic coordinates under the pointer; event.point gives pixel coordinates relative to the container's top-left corner. Use move and zoom for immediate feedback. Prefer moveend and zoomend for data requests or saving state to avoid excessive API calls.

The map below displays event results above the map. Move the pointer to see lngLat; after dragging or zooming, inspect the updated center and zoom:

Move the pointer over the map to see its coordinatesPan or zoom the map to see the moveend result

🧰 Add common controls

map.addControl(new mapboxgl.NavigationControl(), 'top-right')
map.addControl(new mapboxgl.ScaleControl({ unit: 'metric' }), 'bottom-left')
map.addControl(new mapboxgl.GeolocateControl({
    positionOptions: { enableHighAccuracy: true },
    trackUserLocation: true,
}), 'top-right')
  • NavigationControl provides zoom controls and a button to reset the bearing to north.
  • ScaleControl shows the current map scale; metric uses meters and kilometers.
  • GeolocateControl uses browser geolocation, which requires HTTPS or a local development environment and the user's permission.

Location comes from the device and browser. Environmental conditions affect accuracy, so do not assume a location is always available or sufficiently accurate.

The example below shows all three controls: zoom, rotation, and geolocation at the top right, and a scale bar at the bottom left. Clicking geolocation requests browser permission; denying it does not affect the other controls.


💬 Create a basic popup

const popup = new mapboxgl.Popup({ offset: 12 })
    .setLngLat([116.397, 39.909])
    .setText('Current location')
    .addTo(map)

popup.setText('Content updated')
popup.remove()

Prefer setText for plain text. setHTML parses a string as HTML, so sanitize content from APIs or user input before passing it in.

Use the example below to open, close, and update a popup. The popup stays anchored to its geographic coordinates as you drag the map.


🧹 Remove listeners to avoid duplicate handlers

Pass off the same event name and function reference used with on:

function handleMoveEnd() {
    console.log(map.getBounds())
}

map.on('moveend', handleMoveEnd)

function destroyMap() {
    map.off('moveend', handleMoveEnd)
    map.remove()
}

Call destroyMap() when the page or component is destroyed. Two anonymous functions passed separately to on and off are different functions, so the listener will remain registered. Re-entering the page or repeating initialization can then make one action trigger several callbacks.


🧾 Summary

  • Use load for initial resource setup; idle indicates that the current view has settled temporarily.
  • Mouse events provide geographic coordinates through lngLat and pixel coordinates through point.
  • Prefer end events such as moveend and zoomend for API requests.
  • Navigation, scale, and geolocation are common basic controls.
  • Keep the original function reference so you can remove a listener.

❓ Questions and answers

Q1: Why does my idle handler run repeatedly?

The map can become idle again whenever resource loading and animations finish. idle is not a one-time lifecycle hook.

Q2: Why does browser geolocation do nothing?

Check that the page uses HTTPS, the user granted location permission, and the device can provide a location.

Q3: When should I use move versus moveend?

Use move for immediate interface updates and moveend for heavier work such as requests or saving bounds.


🧪 Exercises

  1. Show rounded longitude and latitude in a popup when the map is clicked.
  2. Log the current center and zoom on moveend, and remove the listener on unmount.
// Write your code here

🎉 You now know how to use map events and basic controls!