Skip to main content

Style layers based on geographic inclusion

This example shows how to use a 'within' expression to dynamically style a circle layer based on if a point feature falls within a polygon. Points falling within the state of Colorado are colored #f55442 and those outside of its borders are colored #484848.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Style layers based on geographic inclusion</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v3.5.1/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v3.5.1/mapbox-gl.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
// TO MAKE THE MAP APPEAR YOU MUST
// ADD YOUR ACCESS TOKEN FROM
// https://account.mapbox.com
mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN';
const map = new mapboxgl.Map({
container: 'map', // container ID
// Choose from Mapbox's core styles, or make your own style with Mapbox Studio
style: 'mapbox://styles/mapbox/light-v11', // style URL
center: [-107.1714, 39.1402], // starting position [lng, lat]
zoom: 5 // starting zoom
});

// Geodata for Colorado
const coloradoJSON = {
'type': 'Polygon',
'coordinates': [
[
[-109.05, 41.00069],
[-109.05, 36.99302],
[-102.04209, 36.99302],
[-102.04209, 41.00069],
[-109.05, 41.00069],
[-109.05, 41.00069]
]
]
};

map.on('load', () => {
map.addSource('colorado', {
'type': 'geojson',
'data': {
'type': 'Feature',
'geometry': coloradoJSON
}
});

map.addLayer({
'id': 'colorado',
'type': 'fill',
'source': 'colorado',
'layout': {},
'paint': {
'fill-color': '#088',
'fill-opacity': 0.25
}
});

map.addSource('points', {
type: 'geojson',
data: {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'properties': {},
'geometry': {
'coordinates': [-104.81437, 41.1369],
'type': 'Point'
}
},
{
'type': 'Feature',
'properties': {},
'geometry': {
'coordinates': [-104.975, 39.73785],
'type': 'Point'
}
},
{
'type': 'Feature',
'properties': {},
'geometry': {
'coordinates': [-109.54677, 38.57404],
'type': 'Point'
}
},
{
'type': 'Feature',
'properties': {},
'geometry': {
'coordinates': [-108.55777, 39.06323],
'type': 'Point'
}
},
{
'type': 'Feature',
'properties': {},
'geometry': {
'coordinates': [-105.58906, 41.31104],
'type': 'Point'
}
}
]
}
});

// Apply 'within' expression to points
// Routes within Colorado have 'circle-color': '#f55442'
// Fallback values (routes not within Colorado) have 'circle-color': '#484848'
map.addLayer({
'id': 'points',
'type': 'circle',
'source': 'points',
'layout': {},
'paint': {
'circle-color': [
'case',
['within', coloradoJSON],
'#f55442',
'#484848'
],
'circle-radius': 10
}
});
});
</script>

</body>
</html>
Was this example helpful?