All docsMapbox GL JSExamplesUse a fallback image

Use a fallback image

Use a coalesce expression to display another image when a requested image is not available.

This example uses a GeoJSON source with features that include an icon property. In this case, one feature has an icon property that does not match the name of any image in the Mapbox Light style's sprite. For that feature, the map will display a fallback image of a rocket.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Use a fallback image</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.2.0/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 access token here>';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-77, 38.75],
zoom: 5
});
map.on('load', function () {
// Add a new GeoJSON source with features that include
// an "icon" property. In this case, one feature has an
// "icon" property that does not match the name of any
// image in the style's sprite. For this feature, the map
// will display a fallback image ("rocket-15").
map.addSource('points', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [
-77.03238901390978, 38.913188059745586
]
},
'properties': {
'title': 'Washington DC',
'icon': 'monument'
}
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-79.9959, 40.4406]
},
'properties': {
'title': 'Pittsburgh',
// The Mapbox Light style's sprite does not
// contain an image with the name "bridges-15"
// but we can display a fallback image.
'icon': 'bridges'
}
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-76.2859, 36.8508]
},
'properties': {
'title': 'Norfolk',
'icon': 'harbor'
}
}
]
}
});
map.addLayer({
'id': 'points',
'type': 'symbol',
'source': 'points',
'layout': {
// These icons are a part of the Mapbox Light style.
// To view all images available in a Mapbox style, open
// the style in Mapbox Studio and click the "Images" tab.
// To add a new image to the style at runtime see
// https://docs.mapbox.com/mapbox-gl-js/example/add-image/
'icon-image': [
'coalesce',
['image', ['concat', ['get', 'icon'], '-15']],
// If no image with the name above exists, show the
// "rocket-15" image instead.
['image', 'rocket-15']
],
'text-field': ['get', 'title'],
'text-font': ['Open Sans Semibold', 'Arial Unicode MS Bold'],
'text-offset': [0, 0.6],
'text-anchor': 'top'
}
});
});
</script>
</body>
</html>