Filtering, Visibility, and Layer Management

Build maintainable application layer lists with filters, visibility, and layer ordering, and manage map state consistently.

🎯 Introduction

By the end of this article, you will be able to filter features, hide entire layers, change their drawing order, and fit the camera to a layer's data extent.

Each operation serves a different purpose:

User goalMap operationMethod
Show only online locationsFilter features within a layersetFilter()
Temporarily hide all locationsHide the entire layersetLayoutProperty()
Place points above polygonsChange layer ordermoveLayer()
View all data in a layerAdjust the camerafitBounds()

🧱 Display only matching features

Purpose: show a subset of a layer's features without deleting or requesting data again.

Suppose the places layer contains online and offline points. When the user selects online locations only, filter by each feature's properties.status:

map.setFilter('places', [
    '==',
    ['get', 'status'],
    'online',
])

The expression checks each feature: get reads status, and == tests whether it equals online. Matching points stay visible; other points are temporarily not rendered.

Pass null to clear the filter and show all points again:

map.setFilter('places', null)

Filtering changes only which features a layer draws; it does not delete source data. Below, the left map shows all four points, while the right uses the same data to show only the two green online points.

Before filtering: two online, two offline
After filtering: only the two online points

🧩 Combine multiple filters

Purpose: combine interface options, such as online status and a score of at least 80.

Collect the selected conditions in an array, then use all to require each feature to satisfy every condition:

const conditions = []

if (filters.status !== 'all') {
    conditions.push(['==', ['get', 'status'], filters.status])
}

if (filters.minScore !== null) {
    conditions.push(['>=', ['get', 'score'], filters.minScore])
}

map.setFilter(
    'places',
    conditions.length > 0 ? ['all', ...conditions] : null,
)

all requires every condition; any requires at least one. Pass null when no conditions are selected to avoid confusing results from empty conditions.

Change “Status” and “Minimum score” below to see how both conditions determine the number of visible points.

Showing 4 points

👁 Control entire layers and drawing order

Purpose: show or hide a layer, change its appearance, and determine which layers appear on top.

Show and hide an entire layer

Filters determine which features appear within a layer; visibility determines whether the whole layer appears. When the locations toggle is off, change visibility directly:

map.setLayoutProperty('places', 'visibility', 'none')
map.setLayoutProperty('places', 'visibility', 'visible')

Source data and filters remain intact while hidden. Showing the layer again requires no new data request.

Change a layer's style

You can update color, opacity, and line width after creating a layer:

map.setPaintProperty('places', 'circle-color', '#7c3aed')
map.setPaintProperty('places', 'circle-opacity', 0.6)
map.setPaintProperty('roads', 'line-width', 4)

These methods affect appearance only, leaving application properties unchanged.

Adjust drawing order

When layers overlap, later layers cover earlier ones. Move points above all layers with:

map.moveLayer('places')

Pass a second layer ID to move places before that layer:

map.moveLayer('places', 'areas')

The component below combines all three operations. Hide the point layer, change its style, then move it below the purple polygon layer to see what each operation changes.

Layer panels commonly store names, stable layer IDs, and toggle states in an array:

const mapState = {
    visibility: {
        areas: true,
        roads: true,
        places: true,
    },
    order: ['areas', 'roads', 'places'],
}

Interface buttons update this state and call the corresponding Mapbox methods. Use the same state to restore visibility and order after data refreshes or style reloads.


📐 Fit the map to all data in a layer

Purpose: move the camera to show all the data when the user clicks the fit button, including data currently offscreen.

Calculate bounds from all coordinates in the layer, then pass them to fitBounds():

function focusCoordinates(coordinates: [number, number][]) {
    const bounds = new mapboxgl.LngLatBounds()
    coordinates.forEach(coordinate => bounds.extend(coordinate))

    if (!bounds.isEmpty()) {
        map.fitBounds(bounds, {
            padding: 48,
            maxZoom: 15,
        })
    }
}

bounds is the rectangle enclosing all coordinates. padding leaves space around the data, while maxZoom prevents excessive zooming for a few nearby features.

The map below intentionally starts away from the data. Click “Fit all points” to move and zoom until all three points are visible. Click “Move away” to compare again.

The data is outside the current view. Click “Fit all points” to bring it into view.

Calculate the extent from the layer's original geometry. queryRenderedFeatures() returns only features rendered in the current view and cannot calculate the complete extent of offscreen data.


🧾 Summary

  • setFilter() determines which features appear in a layer.
  • Combine conditions with all or any, and use null when there are none.
  • visibility shows or hides an entire layer without removing source data.
  • setPaintProperty() updates color, opacity, and line width.
  • moveLayer() changes layer drawing order.
  • fitBounds() adjusts the camera to the full data extent.

❓ Questions and answers

Q1: How do filtering and hiding differ?

Filtering excludes nonmatching features; visibility hides the entire layer at once.

Q2: Must I request data again after hiding a layer?

No. The source and filters remain available. Set visibility back to visible.

Q3: Why is some data still missing after fitting the camera?

The bounds were likely calculated only from visible features. Use coordinates from the layer's complete application dataset.


🧪 Exercises

  1. Combine online status with a score of at least 80.
  2. Add a visibility toggle for a point layer and store its current state.
// Write your code here

🎉 You now know how to filter, show, hide, and manage layers!