evergis-mapgl-projects
by Trufi
HTML
<script src="https://mapgl.2gis.com/api/js/v1"></script>
<div id="map"></div>
<div class="layers"></div>
CSS
html,
body,
#map {
width: 100%;
margin: 0;
height: 100%;
overflow: hidden;
}
.layers {
position: absolute;
top: 5px;
left: 5px;
border-radius: 5px;
background: rgba(255, 255, 255, 0.7);
font-size: 10px;
font-weight: 700;
}
.layer {
width: 250px;
margin: 5px;
}
JavaScript
if (!mapgl.isSupported()) {
document.querySelector('#map').innerHTML = `WebGL is not supoorted in your browser!`;
throw new Error('WebGL is not supoorted in your browser!');
}
const map = new mapgl.Map('map', {
key: '042b5b75-f847-4f2a-b695-b5f58adc9dfd ',
center: [47.4936977377508, 26.1686477267334],
zoom: 6,
});
window.addEventListener('resize', () => map.invalidateSize());
const styleLoad = new Promise((res) => {
map.once('styleload', () => res());
});
const addedLayersToStyle = {};
updateData();
setInterval(() => updateData(), 10000);
let source;
async function updateData() {
const rawData = await fetchData();
await styleLoad;
const data = evergisDataToGeoJSON(rawData);
if (source) {
source.setData(data);
} else {
source = new mapgl.GeoJsonSource(map, {
data,
attributes: {
foo: 'bar',
},
});
}
data.features.forEach((feature) => {
const name = feature.properties.layer;
if (!addedLayersToStyle[name]) {
const color = randomColor();
addedLayersToStyle[name] = {
name,
color
};
map.addLayer(createLayer(name, color));
}
});
renderLayersMenu(Object.values(addedLayersToStyle));
console.log(`Data is updated`);
}
function createLayer(name, color) {
return {
id: `my-${name}`,
type: 'polygon',
filter: [
'all',
['match', ['sourceAttr', 'foo'],
['bar'], true, false
],
['match', ['get', 'layer'],
[name], true, false
],
],
style: {
color: color + '77',
},
};
}
function randomColor() {
return `#${hex()}${hex()}${hex()}`;
}
function hex() {
return ('00' + Math.floor(Math.random() * 255).toString(16)).slice(-2);
}
function renderLayersMenu(layers) {
const html = /* HTML */ `<div>${layers.map(renderLayer).join('')}</div>`;
document.querySelector('.layers').innerHTML = html;
}
function renderLayer(layer) {
return /* HTML */ `<div class="layer"...