import { Controller } from '@hotwired/stimulus';
import 'leaflet';
export default class extends Controller {
static values = {
geojson: String,
icon: String,
}
connect() {
const simpleIcon = L.icon({
iconUrl: this.iconValue,
iconSize: [16, 16],
iconAnchor: [8, 16],
popupAnchor: [0, 0],
});
const iconHtml = `
`;
const icons = {
'danger': L.divIcon({ html: iconHtml, className: 'svg-icon text-danger', iconSize: [16, 16], iconAnchor: [8, 16], }),
'warning': L.divIcon({ html: iconHtml, className: 'svg-icon text-warning', iconSize: [16, 16], iconAnchor: [8, 16], }),
'success': L.divIcon({ html: iconHtml, className: 'svg-icon text-success', iconSize: [16, 16], iconAnchor: [8, 16], }),
};
var map = L.map(this.element);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap'
}).addTo(map);
var layer = L.featureGroup();
var geojsons = JSON.parse(this.geojsonValue);
if (geojsons.length > 0) {
geojsons.forEach(function (geojson) {
const feature0 = geojson.features[0].properties;
const polygon = L.geoJSON(geojson, {
style: function (feature) {
var color = 'blue';
switch (feature.properties.color) {
case 'danger' : color = '#dc3545'; break
case 'warning' : color = '#ffc107'; break
case 'success' : color = '#198754'; break
}
return {color: color};
}
}).bindTooltip(feature0.name).addTo(layer).on('click', function (event) {
window.location.href = event.layer.feature.properties.url;
});
L.marker(polygon.getBounds().getCenter(), {
icon: icons[feature0.color],
title: feature0.name,
clickUrl: feature0.url,
}).addTo(layer).on('click', function (event) {
window.location.href = event.target.options.clickUrl;
});
});
layer.addTo(map);
map.fitBounds(layer.getBounds());
}
}
}