Search code examples
mapboxmapbox-gl-jsmapbox-glmapbox-marker

How can I add an icon to switch the mapboxgl style dynamically?


I want to add an icon as below in the mapboxgl view. Working with Angular2

enter image description here

When I click the icon it should automatically switch the styles (streets-v9, satelllite-v9)

I am following the link mapboxgl example


Solution

  • Did you see this API method? https://www.mapbox.com/mapbox-gl-js/api/#map#setstyle

    With that you can set a new style for the map when you e.g. click an icon or press a button or what ever you wish.

    Take this as a reference to build upon:

    https://jsfiddle.net/andi_lo/706pot8L/

    mapboxgl.accessToken = 'pk.eyJ1IjoiZmFyYWRheTIiLCJhIjoiTUVHbDl5OCJ9.buFaqIdaIM3iXr1BOYKpsQ';
    let map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/streets-v9', 
      center: [-1.77, 52.73],
      zoom: 3,
    });
    
    let icon = document.getElementById('icon');
    
    icon.addEventListener('click', function(e) {
    	map.setStyle('mapbox://styles/mapbox/light-v9');
    }, false)
    #icon {
      position: absolute;
      top: 15px;
      left: 15px;
      color: black;
    }
    
    #map {
      height: 500px;
    }
    <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.css" rel="stylesheet"/>
    <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.js"></script>
    
    <div id="map"></div>
    
    <button id="icon">
    Switch layers
    </button>