Filtering, Visibility, and Layer Management
🎯 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 goal | Map operation | Method |
|---|---|---|
| Show only online locations | Filter features within a layer | setFilter() |
| Temporarily hide all locations | Hide the entire layer | setLayoutProperty() |
| Place points above polygons | Change layer order | moveLayer() |
| View all data in a layer | Adjust the camera | fitBounds() |
🧱 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.
🧩 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.
👁 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.
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
allorany, and usenullwhen there are none. visibilityshows 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
- Combine online status with a score of at least 80.
- 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!
