demarches-normaliennes/app/javascript/new_design/champs/carte.js

48 lines
1.4 KiB
JavaScript
Raw Normal View History

2019-04-25 16:30:51 +02:00
import { initMap, drawPolygons, addFreeDrawEvents } from '../../shared/carte';
2018-10-17 12:07:12 +02:00
2019-04-25 16:30:51 +02:00
async function initialize() {
const elements = document.querySelectorAll('.carte');
if (elements.length) {
const editable = [...elements].find(element =>
element.classList.contains('edit')
);
await loadLeaflet(editable);
for (let element of elements) {
diplayMap(element, null, true);
}
2018-10-17 12:07:12 +02:00
}
2019-04-25 16:30:51 +02:00
}
2018-10-17 12:07:12 +02:00
2019-04-25 16:30:51 +02:00
// We load leaflet dynamically, ramda and freedraw and assign them to globals.
// Latest freedraw version build needs globals.
async function loadLeaflet(editable) {
window.L = await import('leaflet').then(({ default: L }) => L);
if (editable) {
window.R = await import('ramda').then(({ default: R }) => R);
await import('leaflet-freedraw/dist/leaflet-freedraw.web.js');
}
2018-10-17 12:07:12 +02:00
}
function diplayMap(element, data, initial = false) {
data = data || JSON.parse(element.dataset.geo);
2019-04-25 16:30:51 +02:00
const editable = element.classList.contains('edit');
const map = initMap(element, data.position, editable);
2018-10-17 12:07:12 +02:00
2019-04-25 16:30:51 +02:00
drawPolygons(map, data, { initial, editable });
2018-10-17 12:07:12 +02:00
2019-04-25 16:30:51 +02:00
if (initial && editable) {
const input = element.parentElement.querySelector('input[data-remote]');
addFreeDrawEvents(map, input);
2018-10-17 12:07:12 +02:00
}
}
addEventListener('turbolinks:load', initialize);
2019-04-25 16:30:51 +02:00
addEventListener('carte:update', ({ detail: { selector, data } }) => {
const element = document.querySelector(selector);
diplayMap(element, data);
2018-10-17 12:07:12 +02:00
});