Modifying current map style in runtime
In order to modify current style the map instance has two methods: addLayer and removeLayer.
Adding a new layer to the map style
After creating a map, its style will be empty until it is loaded from the server. It is important to add new layers only after style loading because the loaded style will completely overwrite the old one. To do this, the example above uses styleload
event, which is emitted every time after a new style is set:
map.on('styleload', () => {
map.addLayer(layer);
});
If you change a map style with map.setStyleById()
method, you can also use Promise that the method returns:
map.setStyleById('e05ac437-fcc2-4845-ad74-b1de9ce07555').then(() => {
map.addLayer(layer);
});
Adding before another layer
Layers of a map style are ordered relative to each other. The order of the layers determines the sequence in which they are drawn on the map.
By default, the map.addLayer(layer)
method adds a new layer to the end of the layers list, i.e. the new layer will be drawn last. If you need to add the layer not at the end, but before of another layer, you need to specify the ID of another layer in the method as the second argument:
map.addLayer(anotherLayer, 'my-polygons-layer');
You can also add the layer before the layers that are configured in the Style editor:
map.addLayer(layer, 'other roads');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>2GIS Map API</title>
<meta name="description" content="map.addLayer under roads example" />
<style>
html,
body,
#container {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="https://mapgl.2gis.com/api/js/v1"></script>
<script>
const map = new mapgl.Map('container', {
center: [55.425, 25.355],
zoom: 13,
key: 'Your API access key',
});
const layer = {
"id": "newLayer",
"name": "Country, 2GIS",
"type": "polygon",
"style": {
"color": "#949494ee",
"visibility": "visible"
},
"filter": [
"match",
[
"get",
"sublayer"
],
[
"Country_2gis_area"
],
true,
false
]
}
map.on('styleload', () => {
map.addLayer(layer, 'other roads');
});
</script>
</body>