Change a map's style
This example adds a clickable interface that enables a user to apply several different styles to the map.
When the user clicks a style name, it uses setStyle
to redraw the map using the style URL associated with that option.
The map is centered at -2.81361, 36.77271
near El Ejido, Spain, an area known as the "Sea of Plastic" due to the many white-roofed greenhouses in the region, visible in the satellite imagery.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>Change a map's style</title><meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no"><link href="https://api.mapbox.com/mapbox-gl-js/v3.0.1/mapbox-gl.css" rel="stylesheet"><script src="https://api.mapbox.com/mapbox-gl-js/v3.0.1/mapbox-gl.js"></script><style>body { margin: 0; padding: 0; }#map { position: absolute; top: 0; bottom: 0; width: 100%; }</style></head><body><style>#menu {position: absolute;background: #efefef;padding: 10px;font-family: 'Open Sans', sans-serif;}</style> <div id="map"></div> <div id="menu"><input id="satellite-streets-v12" type="radio" name="rtoggle" value="satellite" checked="checked"><!-- See a list of Mapbox-hosted public styles at --><!-- https://docs.mapbox.com/api/maps/styles/#mapbox-styles --><label for="satellite-streets-v12">satellite streets</label><input id="light-v11" type="radio" name="rtoggle" value="light"><label for="light-v11">light</label><input id="dark-v11" type="radio" name="rtoggle" value="dark"><label for="dark-v11">dark</label><input id="streets-v12" type="radio" name="rtoggle" value="streets"><label for="streets-v12">streets</label><input id="outdoors-v12" type="radio" name="rtoggle" value="outdoors"><label for="outdoors-v12">outdoors</label></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 Studiostyle: 'mapbox://styles/mapbox/satellite-streets-v12', // style URLcenter: [-2.81361, 36.77271], // starting position [lng, lat]zoom: 13 // starting zoom}); const layerList = document.getElementById('menu');const inputs = layerList.getElementsByTagName('input'); for (const input of inputs) {input.onclick = (layer) => {const layerId = layer.target.id;map.setStyle('mapbox://styles/mapbox/' + layerId);};}</script> </body></html>
Was this example helpful?