Feature Clicks, Queries, and Highlighting

Click and query map features, read application properties, and use feature-state for hover and selection highlighting.

🎯 Introduction

By the end of this article, you will be able to identify clicked features, read their properties, and indicate hover and selection through color and size.

A common use case is showing details beside the map when a point is clicked. A Point represents a location, a feature combines geometry with application properties, and a layer renders those features as circles.


🖱 Read feature information after clicking a circle

Purpose: identify the clicked feature and retrieve the data needed for its details.

Suppose a map has three locations. Clicking “Location B” should provide its ID, name, and status so the page can open its details. Attach a click handler to the relevant layer:

function handlePlaceClick(event: mapboxgl.MapLayerMouseEvent) {
    const feature = event.features?.[0]
    if (!feature) return

    selectedId.value = feature.id
    selectedProperties.value = feature.properties
}

map.on('click', 'places', handlePlaceClick)

'places' is the clickable layer ID, so clicking the basemap or another layer does not invoke handlePlaceClick. event.features[0] is the first feature hit at that location:

  • feature.id identifies the feature.
  • feature.properties contains application fields such as name and status.

Clickable features should also provide a pointer cue. Show a pointer cursor over circles and reset it on exit:

map.on('mouseenter', 'places', () => {
    map.getCanvas().style.cursor = 'pointer'
})

map.on('mouseleave', 'places', () => {
    map.getCanvas().style.cursor = ''
})

The component below implements this code. Click any blue circle to display its ID, name, and status above the map. The cursor also changes when it enters a circle.

Click a point to see its ID, name, and status

🔎 Check whether a click hits a feature

Purpose: explicitly query which features are rendered at a screen position.

A layer click handler runs only when a circle is hit. To also detect clicks on empty map space, use queryRenderedFeatures(). It queries rendered features at a pixel position in the current view:

map.on('click', (event) => {
    const features = map.queryRenderedFeatures(event.point, {
        layers: ['places'],
    })

    if (features.length === 0) {
        selectedId.value = undefined
        return
    }

    selectedId.value = features[0].id
})

event.point is the pointer position inside the container, and layers restricts the query to interactive layers. An empty result means there is no target feature, so you can close details or clear selection.

This queries features rendered in the current view, rather than all source data. Hidden, filtered, and offscreen features are not returned.

Click a purple circle and then empty space below to see why the query returns 1 and 0 features, respectively.

Click a point or the map background to compare query results

✨ Make hover and selection visible

Purpose: indicate which feature the pointer is over and which feature is selected through color and size.

feature-state stores temporary display state for individual features in Mapbox. It suits hover and selected without modifying the original GeoJSON.

First, let the layer choose circle styles from state:

map.addLayer({
    id: 'places',
    type: 'circle',
    source: 'places-source',
    paint: {
        'circle-radius': [
            'case',
            ['boolean', ['feature-state', 'selected'], false], 13,
            ['boolean', ['feature-state', 'hover'], false], 10,
            6,
        ],
        'circle-color': [
            'case',
            ['boolean', ['feature-state', 'selected'], false], '#dc2626',
            ['boolean', ['feature-state', 'hover'], false], '#f59e0b',
            '#2563eb',
        ],
    },
})

The expression makes normal circles blue, hovered circles larger and orange, and selected circles larger still and red.

Next, update hover as the pointer moves. Clear the previous feature's state before setting the new one:

let hoveredId: string | number | undefined

function setHovered(nextId: string | number | undefined) {
    if (hoveredId !== undefined) {
        map.setFeatureState(
            { source: 'places-source', id: hoveredId },
            { hover: false },
        )
    }

    hoveredId = nextId

    if (nextId !== undefined) {
        map.setFeatureState(
            { source: 'places-source', id: nextId },
            { hover: true },
        )
    }
}

Handle selection the same way. Keep one selectedId in Vue and share it across map clicks, list clicks, and the detail panel to avoid conflicting selections:

watch(selectedId, (nextId, previousId) => {
    if (previousId !== undefined) {
        map.setFeatureState(
            { source: 'places-source', id: previousId },
            { selected: false },
        )
    }

    if (nextId !== undefined) {
        map.setFeatureState(
            { source: 'places-source', id: nextId },
            { selected: true },
        )
    }
})

setFeatureState() requires stable feature IDs. Set id directly on GeoJSON features, or configure promoteId: 'businessId' on the source if the ID is stored in properties.businessId.

Hover over a circle below, then click it. You will see orange hover and red selection states in sequence. Click empty map space to clear selection.

Hover over a point, then click to select it

⚠️ Rendered queries do not return the full dataset

queryRenderedFeatures() returns features currently rendered in the view. Features outside the viewport, excluded by filter, hidden at the current zoom level, or not yet rendered are absent.

Pass a screen rectangle to enlarge the hit area around the pointer:

const padding = 5
const box = [
    [event.point.x - padding, event.point.y - padding],
    [event.point.x + padding, event.point.y + padding],
]

const features = map.queryRenderedFeatures(box, {
    layers: ['place-circles'],
})

This makes thin lines or small points easier to click, but does not replace a full data query. To search offscreen features, paginate, or retrieve complete geometry, query the application API or original data, then display the results on the map.


🧾 Summary

  • Layer click events identify the feature a user clicked.
  • Feature IDs establish identity; properties supplies application information.
  • queryRenderedFeatures() checks whether a click hits a target feature.
  • Results depend on the viewport, filters, and zoom level.
  • feature-state stores temporary display state without modifying GeoJSON.
  • Clear the previous feature's state when changing hover or selection.
  • Share one selectedId across the map, list, and detail panel in Vue.

❓ Questions and answers

Q1: Why can't I read an ID after clicking a circle?

The GeoJSON feature has no id, and the source does not specify an application ID through promoteId.

Q2: Why do all circles remain highlighted after the pointer passes over them?

The previous feature was not reset to hover: false before the new feature received hover: true.

Q3: Why doesn't clicking empty space close the details?

Layer click events do not fire over empty space. Listen for map clicks and check whether queryRenderedFeatures() returns an empty result.


🧪 Exercises

  1. Display a circle's name and status on the page when clicked.
  2. Clear selectedId and details when empty map space is clicked.
// Write your code here

🎉 You now know how to query and highlight clicked features!