Examples
Styles (11)Add a default markerAdd an animated icon to the mapAdd a generated icon to the mapGenerate and add a missing icon to the mapAdd a stretchable image to the mapAdd an icon to the mapDisplay a map with a custom styleRender world copiesDisplay a satellite mapChange a map's styleDisplay a mapLayers (32)Display buildings in 3DExtrude polygons for 3D indoor mappingAdd a 3D modelAdjust a layer's opacityAnimate a lineAnimate a series of imagesAnimate a pointChange building color based on zoom levelChange the case of labelsDisplay HTML clusters with custom propertiesCreate and style clustersChange a layer's color with buttonsAdd a custom style layerStyle circles with a data-driven propertyStyle lines with a data-driven propertyDisplay and style rich text labelsUse a fallback imageAdd a pattern to a polygonAdd a new layer below labelsAdd a GeoJSON lineDraw GeoJSON pointsCreate a heatmap layerAdd a GeoJSON polygonAdd hillshadingCreate a gradient line using an expressionAdd multiple geometries from one GeoJSON sourceStyle ocean depth dataShow and hide layersUpdate a choropleth layer by zoom levelChange worldview of administrative boundariesVariable label placementVisualize population densitySources (10)Add a canvas sourceJoin local JSON data with vector tile geometriesAdd an imageAdd live realtime dataUpdate a feature in realtimeAdd a raster tile sourceAdd a third party vector tile sourceAdd a vector tile sourceAdd a videoAdd a WMS sourceUser interaction (21)Customize camera animationsAnimate 3D buildings based on ambient soundsDisable map rotationCreate a draggable MarkerCreate a draggable pointFilter features within map viewFilter symbols by text inputCreate a hover effectDisplay a non-interactive mapChange a map's languageMeasure distancesGet coordinates of the mouse pointerHighlight features containing similar dataGet features under the mouse pointerSelect features around a clicked pointRestrict map panning to an areaFilter symbols by toggling a listCreate a time sliderHighlight features within a bounding boxFit to the bounds of a LineStringToggle interactionsCamera (12)Animate map camera around a pointAnimate a point along a routeCenter the map on a clicked symbolSlowly fly to a locationFly to a locationNavigate the map with game-like controlsJump to a series of locationsOffset the vanishing point using paddingPlay map locations as a slideshowFly to a location based on scroll positionSet pitch and bearingFit a map to a bounding boxControls and overlays (17)Animate a markerChange the default position for attributionAdd custom icons with MarkersDisable scroll zoomView a fullscreen mapLocate the userSwipe between mapsShow drawn polygon areaDisplay driving directionsAdd a geocoderAdd a marker using a place nameDisplay map navigation controlsShow polygon information on clickDisplay a popup on clickDisplay a popup on hoverDisplay a popupAttach a popup to a marker instanceGeocoder (9)Supplement forward geocoding search results from another data sourceAccept coordinates as input to a geocoderUse a custom render function with a geocoderUse the geocoder without a mapLimit geocoder results to a named regionUse a custom camera animation with a geocoderPlace the geocoder input outside the mapLocalize the geocoder to a given languageSet a point after Geocoder resultBrowser support (1)Check if Mapbox GL JS is supportedInternationalization support (2)Use locally generated ideographsAdd support for right-to-left scripts

Filter features within map view

Move the map to query viewable features in a vector tile layer and filter by typing in an input.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Filter features within map view</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v1.10.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.10.1/mapbox-gl.css" rel="stylesheet" />
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<style>
#map {
position: absolute;
left: 25%;
top: 0;
bottom: 0;
width: 75%;
}
.map-overlay {
position: absolute;
width: 25%;
top: 0;
bottom: 0;
left: 0;
font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
background-color: #fff;
max-height: 100%;
overflow: hidden;
}
.map-overlay fieldset {
display: none;
background: #ddd;
border: none;
padding: 10px;
margin: 0;
}
.map-overlay input {
display: block;
border: none;
width: 100%;
border-radius: 3px;
padding: 10px;
margin: 0;
box-sizing: border-box;
}
.map-overlay .listing {
overflow: auto;
max-height: 100%;
}
.map-overlay .listing > * {
display: block;
padding: 5px 10px;
margin: 0;
}
.map-overlay .listing a {
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
color: #404;
text-decoration: none;
}
.map-overlay .listing a:last-child {
border: none;
}
.map-overlay .listing a:hover {
background: #f0f0f0;
}
</style>
<div id="map"></div>
<div class="map-overlay">
<fieldset>
<input
id="feature-filter"
type="text"
placeholder="Filter results by name"
/>
</fieldset>
<div id="feature-listing" class="listing"></div>
</div>
<script>
// TO MAKE THE MAP APPEAR YOU MUST
// ADD YOUR ACCESS TOKEN FROM
// https://account.mapbox.com
mapboxgl.accessToken = '<your access token here>';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-98, 38.88],
maxZoom: 5,
minZoom: 1,
zoom: 3
});
// Holds visible airport features for filtering
var airports = [];
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false
});
var filterEl = document.getElementById('feature-filter');
var listingEl = document.getElementById('feature-listing');
function renderListings(features) {
var empty = document.createElement('p');
// Clear any existing listings
listingEl.innerHTML = '';
if (features.length) {
features.forEach(function(feature) {
var prop = feature.properties;
var item = document.createElement('a');
item.href = prop.wikipedia;
item.target = '_blank';
item.textContent = prop.name + ' (' + prop.abbrev + ')';
item.addEventListener('mouseover', function() {
// Highlight corresponding feature on the map
popup
.setLngLat(feature.geometry.coordinates)
.setText(
feature.properties.name +
' (' +
feature.properties.abbrev +
')'
)
.addTo(map);
});
listingEl.appendChild(item);
});
// Show the filter input
filterEl.parentNode.style.display = 'block';
} else if (features.length === 0 && filterEl.value !== '') {
empty.textContent = 'No results found';
listingEl.appendChild(empty);
} else {
empty.textContent = 'Drag the map to populate results';
listingEl.appendChild(empty);
// Hide the filter input
filterEl.parentNode.style.display = 'none';
// remove features filter
map.setFilter('airport', ['has', 'abbrev']);
}
}
function normalize(string) {
return string.trim().toLowerCase();
}
function getUniqueFeatures(array, comparatorProperty) {
var existingFeatureKeys = {};
// Because features come from tiled vector data, feature geometries may be split
// or duplicated across tile boundaries and, as a result, features may appear
// multiple times in query results.
var uniqueFeatures = array.filter(function(el) {
if (existingFeatureKeys[el.properties[comparatorProperty]]) {
return false;
} else {
existingFeatureKeys[el.properties[comparatorProperty]] = true;
return true;
}
});
return uniqueFeatures;
}
map.on('load', function() {
map.addSource('airports', {
'type': 'vector',
'url': 'mapbox://mapbox.04w69w5j'
});
map.addLayer({
'id': 'airport',
'source': 'airports',
'source-layer': 'ne_10m_airports',
'type': 'symbol',
'layout': {
'icon-image': 'airport-15',
'icon-padding': 0,
'icon-allow-overlap': true
}
});
map.on('moveend', function() {
var features = map.queryRenderedFeatures({ layers: ['airport'] });
if (features) {
var uniqueFeatures = getUniqueFeatures(features, 'iata_code');
// Populate features for the listing overlay.
renderListings(uniqueFeatures);
// Clear the input container
filterEl.value = '';
// Store the current features in sn `airports` variable to
// later use for filtering on `keyup`.
airports = uniqueFeatures;
}
});
map.on('mousemove', 'airport', function(e) {
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = 'pointer';
// Populate the popup and set its coordinates based on the feature.
var feature = e.features[0];
popup
.setLngLat(feature.geometry.coordinates)
.setText(
feature.properties.name +
' (' +
feature.properties.abbrev +
')'
)
.addTo(map);
});
map.on('mouseleave', 'airport', function() {
map.getCanvas().style.cursor = '';
popup.remove();
});
filterEl.addEventListener('keyup', function(e) {
var value = normalize(e.target.value);
// Filter visible features that don't match the input value.
var filtered = airports.filter(function(feature) {
var name = normalize(feature.properties.name);
var code = normalize(feature.properties.abbrev);
return name.indexOf(value) > -1 || code.indexOf(value) > -1;
});
// Populate the sidebar with filtered results
renderListings(filtered);
// Set the filter to populate features into the layer.
if (filtered.length) {
map.setFilter('airport', [
'match',
['get', 'abbrev'],
filtered.map(function(feature) {
return feature.properties.abbrev;
}),
true,
false
]);
}
});
// Call this function on initialization
// passing an empty array to render an empty state
renderListings([]);
});
</script>
</body>
</html>
Was this example helpful?