evergis-leaflet-projects
by Trufi
HTML
<script src="https://maps.api.2gis.ru/2.0/loader.js"></script>
<div id="map"></div>
<div class="ui"></div>
CSS
html,
body,
#map {
width: 100%;
margin: 0;
height: 100%;
overflow: hidden;
}
.ui {
position: absolute;
top: 5px;
left: 5px;
border-radius: 5px;
background: rgba(255, 255, 255, 0.9);
font-size: 15px;
padding: 5px;
}
.title {
font-size: 20px;
}
.project {
height: 20px;
width: 250px;
line-height: 20px;
border: 1px solid transparent;
margin: 0 0 5px 0;
cursor: pointer;
background: #e7e7e7;
padding: 0 5px;
}
.project:hover {
background: #e0e0e0;
}
.project.active {
border-color: #000000;
}
.item {
margin: 5px;
width: 250px;
display: flex;
justify-content: space-between;
}
JavaScript
const auth = {
username: 'sbgisuser',
password: 'D<mANDN/8bNn,+3j',
};
const defaultProjectAlias = 'High way patrol';
let map;
const addedLayersToStyle = {};
DG.then(() => {
map = DG.map('map', {
center: [26.1686477267334, 47.4936977377508],
zoom: 6,
});
updateData();
setInterval(() => updateData(), 15000);
});
let geojson;
let activeProjectName;
let projectsData;
async function updateData() {
projectsData = await fetchData();
if (!activeProjectName) {
const defaultProject = Object.values(projectsData).find(
(project) => project.alias === defaultProjectAlias,
);
if (defaultProject) {
activeProjectName = defaultProject.name;
} else {
activeProjectName = Object.keys(projectsData)[0];
}
}
updateMap();
updateUI();
}
function getLayerStyle(name) {
if (!addedLayersToStyle[name]) {
const color = randomColor();
const r = 6;
addedLayersToStyle[name] = {
name,
color,
icon: L.icon({
iconUrl: circleIcon(color, r),
iconSize: [r * 2, r * 2],
iconAnchor: [r, r],
}),
};
}
return addedLayersToStyle[name];
}
function updateMap() {
const project = projectsData[activeProjectName];
const newGeoJson = {
type: 'FeatureCollection',
features: [],
};
Object.values(project.items).forEach((item) => {
if (!item.isVisible) {
return;
}
newGeoJson.features.push(...item.features);
});
if (geojson) {
geojson.remove();
}
geojson = L.geoJSON(newGeoJson, {
pointToLayer: (feature, latlng) => {
return L.marker(latlng, {
icon: getLayerStyle(feature.properties.itemName).icon,
});
},
style: (feature) => {
return {
color: getLayerStyle(feature.properties.itemName).color,
fillOpacity: 0.5,
weight: 1,
};
},
});
geojson.addTo(map);
}
function randomColor() {
return `#${hex()}${hex()}${hex()}`;
}
function hex() {
return ('00' +...