'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
When I click the icon it should automatically switch the styles (streets-v9, satelllite-v9)
I am following the link mapboxgl example
Solution 1:[1]
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>
Solution 2:[2]
What you want is a "control" that switches layers. Mapbox-GL-JS doesn't include such a thing, nor is there one listed as a plugin (yet).
You should use Mapbox-GL-JS's iControl class to create the control, then add styling and behaviour following Mapbox's instructions:
function LayerSwitchControl() { }
LayerSwitchControl.prototype.onAdd = function(map) {
this._map = map;
this._container = document.createElement('div');
this._container.className = 'mapboxgl-ctrl';
// change this next line to include a layer-switching icon
this._container.textContent = 'Hello, world';
return this._container;
};
LayerSwitchControl.prototype.onRemove = function () {
this._container.parentNode.removeChild(this._container);
this._map = undefined;
};
You'll then need to add code to:
- Add the control
- Respond to
click
events as appropriate.
Solution 3:[3]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Andi-lo |
Solution 2 | Community |
Solution 3 | hoogw |