Refactor leaflet code for better loading

This commit is contained in:
Paul Chavard 2019-12-19 00:33:46 +01:00
parent a223eb05da
commit 7ebebf2e80
4 changed files with 267 additions and 209 deletions

View file

@ -1,47 +1,38 @@
import { initMap, drawPolygons, addFreeDrawEvents } from '../../shared/carte';
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);
loadAndDrawMap(element);
}
}
}
// 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);
async function loadAndDrawMap(element) {
const data = JSON.parse(element.dataset.geo);
const editable = element.classList.contains('edit');
if (editable) {
window.R = await import('ramda').then(({ default: R }) => R);
await import('leaflet-freedraw/dist/leaflet-freedraw.web.js');
const { drawEditableMap } = await import('../../shared/carte-editor');
drawEditableMap(element, data);
} else {
const { drawMap } = await import('../../shared/carte');
drawMap(element, data);
}
}
function diplayMap(element, data, initial = false) {
data = data || JSON.parse(element.dataset.geo);
const editable = element.classList.contains('edit');
const map = initMap(element, data.position, editable);
async function loadAndRedrawMap(element, data) {
const { redrawMap } = await import('../../shared/carte-editor');
drawPolygons(map, data, { initial, editable });
if (initial && editable) {
const input = element.parentElement.querySelector('input[data-remote]');
addFreeDrawEvents(map, input);
}
redrawMap(element, data);
}
addEventListener('turbolinks:load', initialize);
addEventListener('carte:update', ({ detail: { selector, data } }) => {
const element = document.querySelector(selector);
diplayMap(element, data);
loadAndRedrawMap(element, data);
});

View file

@ -0,0 +1,214 @@
import L from 'leaflet';
import FreeDraw from 'leaflet-freedraw';
import { fire, delegate } from '@utils';
import $ from 'jquery';
import polygonArea from './polygon_area';
const MAPS = new WeakMap();
export function drawEditableMap(element, data) {
const map = initMap(element, data);
drawCadastre(map, data);
drawQuartiersPrioritaires(map, data);
drawParcellesAgricoles(map, data);
drawUserSelectionEditor(map, data);
const input = element.parentElement.querySelector('input[data-remote]');
addFreeDrawEvents(map, input);
}
export function redrawMap(element, data) {
const map = initMap(element, data);
clearLayers(map);
drawCadastre(map, data);
drawQuartiersPrioritaires(map, data);
drawParcellesAgricoles(map, data);
bringToFrontUserSelection(map);
}
function initMap(element, { position }) {
if (MAPS.has(element)) {
return MAPS.get(element);
} else {
const map = L.map(element, {
scrollWheelZoom: false
}).setView([position.lat, position.lon], 18);
const loadTilesLayer = process.env.RAILS_ENV != 'test';
if (loadTilesLayer) {
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
}
const freeDraw = new FreeDraw({
mode: FreeDraw.NONE,
smoothFactor: 4,
mergePolygons: false
});
map.addLayer(freeDraw);
map.freeDraw = freeDraw;
MAPS.set(element, map);
return map;
}
}
function toLatLngs({ coordinates }) {
return coordinates.map(polygon =>
polygon[0].map(point => L.GeoJSON.coordsToLatLng(point))
);
}
function drawUserSelectionEditor(map, { selection }) {
if (selection) {
const geoJSON = L.geoJSON(selection);
for (let polygon of toLatLngs(selection)) {
map.freeDraw.create(polygon);
}
map.fitBounds(geoJSON.getBounds());
}
}
export function addFreeDrawEvents(map, selector) {
const input = findInput(selector);
map.freeDraw.on('markers', ({ latLngs }) => {
if (latLngs.length === 0) {
input.value = EMPTY_GEO_JSON;
} else if (polygonArea(latLngs) < 300000) {
input.value = JSON.stringify(latLngs);
} else {
input.value = ERROR_GEO_JSON;
}
fire(input, 'change');
});
}
function drawCadastre(map, { cadastres }) {
drawLayer(map, cadastres, CADASTRE_POLYGON_STYLE);
}
function drawQuartiersPrioritaires(map, { quartiersPrioritaires }) {
drawLayer(map, quartiersPrioritaires, QP_POLYGON_STYLE);
}
function drawParcellesAgricoles(map, { parcellesAgricoles }) {
drawLayer(map, parcellesAgricoles, RPG_POLYGON_STYLE);
}
function getCurrentMap(element) {
if (!element.matches('.carte')) {
const closestCarteElement = element.closest('.carte');
const closestToolbarElement = element.closest('.toolbar');
element = closestCarteElement
? closestCarteElement
: closestToolbarElement.parentElement.querySelector('.carte');
}
if (MAPS.has(element)) {
return MAPS.get(element);
}
}
const EMPTY_GEO_JSON = '[]';
const ERROR_GEO_JSON = '';
function findInput(selector) {
return typeof selector === 'string'
? document.querySelector(selector)
: selector;
}
function clearLayers(map) {
map.eachLayer(layer => {
if (layer instanceof L.GeoJSON) {
map.removeLayer(layer);
}
});
}
function bringToFrontUserSelection(map) {
for (let layer of map.freeDraw.all()) {
layer.bringToFront();
}
}
function drawLayer(map, data, style) {
if (Array.isArray(data) && data.length > 0) {
const layer = new L.GeoJSON(undefined, {
interactive: false,
style
});
for (let { geometry } of data) {
layer.addData(geometry);
}
layer.addTo(map);
}
}
const POLYGON_STYLE = {
weight: 2,
opacity: 0.3,
color: 'white',
dashArray: '3',
fillOpacity: 0.7
};
const CADASTRE_POLYGON_STYLE = Object.assign({}, POLYGON_STYLE, {
fillColor: '#8a6d3b'
});
const QP_POLYGON_STYLE = Object.assign({}, POLYGON_STYLE, {
fillColor: '#31708f'
});
const RPG_POLYGON_STYLE = Object.assign({}, POLYGON_STYLE, {
fillColor: '#31708f'
});
delegate('click', '.carte.edit', event => {
const map = getCurrentMap(event.target);
if (map) {
const isPath = event.target.matches('.leaflet-container g path');
if (isPath) {
setTimeout(() => {
map.freeDraw.mode(FreeDraw.EDIT | FreeDraw.DELETE);
}, 50);
} else {
map.freeDraw.mode(FreeDraw.NONE);
}
}
});
delegate('click', '.toolbar .new-area', event => {
event.preventDefault();
const map = getCurrentMap(event.target);
if (map) {
map.freeDraw.mode(FreeDraw.CREATE);
}
});
$(document).on('select2:select', 'select[data-address]', event => {
const map = getCurrentMap(event.target);
const { geometry } = event.params.data;
if (map && geometry && geometry.type === 'Point') {
const [lon, lat] = geometry.coordinates;
map.setView(new L.LatLng(lat, lon), 14);
}
});

View file

@ -1,18 +1,23 @@
/* globals FreeDraw L */
import { fire, delegate } from '@utils';
import $ from 'jquery';
import polygonArea from './polygon_area';
import L from 'leaflet';
const MAPS = new WeakMap();
export function initMap(element, position, editable = false) {
export function drawMap(element, data) {
const map = initMap(element, data);
drawCadastre(map, data);
drawQuartiersPrioritaires(map, data);
drawParcellesAgricoles(map, data);
drawUserSelection(map, data);
}
function initMap(element, { position }) {
if (MAPS.has(element)) {
return MAPS.get(element);
} else {
const map = L.map(element, {
scrollWheelZoom: false
}).setView([position.lat, position.lon], editable ? 18 : position.zoom);
}).setView([position.lat, position.lon], position.zoom);
const loadTilesLayer = process.env.RAILS_ENV != 'test';
if (loadTilesLayer) {
@ -22,168 +27,47 @@ export function initMap(element, position, editable = false) {
}).addTo(map);
}
if (editable) {
const freeDraw = new FreeDraw({
mode: FreeDraw.NONE,
smoothFactor: 4,
mergePolygons: false
});
map.addLayer(freeDraw);
map.freeDraw = freeDraw;
}
MAPS.set(element, map);
return map;
}
}
export function drawPolygons(map, data, { editable, initial }) {
if (initial) {
drawUserSelection(map, data, editable);
}
clearLayers(map);
drawCadastre(map, data, editable);
drawQuartiersPrioritaires(map, data, editable);
drawParcellesAgricoles(map, data, editable);
bringToFrontUserSelection(map);
}
export function drawUserSelection(map, { selection }, editable = false) {
function drawUserSelection(map, { selection }) {
if (selection) {
const coordinates = toLatLngs(selection);
let polygon;
const layer = L.geoJSON(selection, {
style: USER_SELECTION_POLYGON_STYLE
});
if (editable) {
coordinates.forEach(polygon => map.freeDraw.create(polygon));
[polygon] = markFreeDrawLayers(map);
} else {
polygon = L.polygon(coordinates, {
color: 'red',
zIndex: 3
});
polygon.addTo(map);
}
layer.addTo(map);
if (polygon) {
map.fitBounds(polygon.getBounds());
}
map.fitBounds(layer.getBounds());
}
}
export function addFreeDrawEvents(map, selector) {
const input = findInput(selector);
map.freeDraw.on('markers', ({ latLngs }) => {
if (latLngs.length === 0) {
input.value = EMPTY_GEO_JSON;
} else if (polygonArea(latLngs) < 300000) {
input.value = JSON.stringify(latLngs);
} else {
input.value = ERROR_GEO_JSON;
}
markFreeDrawLayers(map);
fire(input, 'change');
});
function drawCadastre(map, { cadastres }) {
drawLayer(map, cadastres, noEditStyle(CADASTRE_POLYGON_STYLE));
}
function drawCadastre(map, { cadastres }, editable = false) {
drawLayer(
map,
cadastres,
editable ? CADASTRE_POLYGON_STYLE : noEditStyle(CADASTRE_POLYGON_STYLE)
);
function drawQuartiersPrioritaires(map, { quartiersPrioritaires }) {
drawLayer(map, quartiersPrioritaires, noEditStyle(QP_POLYGON_STYLE));
}
function drawQuartiersPrioritaires(
map,
{ quartiersPrioritaires },
editable = false
) {
drawLayer(
map,
quartiersPrioritaires,
editable ? QP_POLYGON_STYLE : noEditStyle(QP_POLYGON_STYLE)
);
}
function drawParcellesAgricoles(map, { parcellesAgricoles }, editable = false) {
drawLayer(
map,
parcellesAgricoles,
editable ? RPG_POLYGON_STYLE : noEditStyle(RPG_POLYGON_STYLE)
);
}
function getCurrentMap(element) {
if (!element.matches('.carte')) {
const closestCarteElement = element.closest('.carte');
const closestToolbarElement = element.closest('.toolbar');
element = closestCarteElement
? closestCarteElement
: closestToolbarElement.parentElement.querySelector('.carte');
}
if (MAPS.has(element)) {
return MAPS.get(element);
}
}
const EMPTY_GEO_JSON = '[]';
const ERROR_GEO_JSON = '';
function toLatLngs({ coordinates }) {
return coordinates.map(polygon =>
polygon[0].map(point => ({ lng: point[0], lat: point[1] }))
);
}
function findInput(selector) {
return typeof selector === 'string'
? document.querySelector(selector)
: selector;
}
function createLayer(map) {
const layer = new L.GeoJSON(undefined, {
interactive: false
});
layer.addTo(map);
return layer;
}
function clearLayers(map) {
map.eachLayer(layer => {
if (layer instanceof L.GeoJSON) {
map.removeLayer(layer);
}
});
}
function bringToFrontUserSelection(map) {
map.eachLayer(layer => {
if (layer.isFreeDraw) {
layer.bringToFront();
}
});
}
function markFreeDrawLayers(map) {
return map.freeDraw.all().map(layer => {
layer.isFreeDraw = true;
return layer;
});
function drawParcellesAgricoles(map, { parcellesAgricoles }) {
drawLayer(map, parcellesAgricoles, noEditStyle(RPG_POLYGON_STYLE));
}
function drawLayer(map, data, style) {
if (Array.isArray(data) && data.length > 0) {
const layer = createLayer(map);
data.forEach(function(item) {
layer.addData(item.geometry);
const layer = new L.GeoJSON(undefined, {
interactive: false,
style
});
layer.setStyle(style).addTo(map);
for (let { geometry } of data) {
layer.addData(geometry);
}
layer.addTo(map);
}
}
@ -215,36 +99,6 @@ const RPG_POLYGON_STYLE = Object.assign({}, POLYGON_STYLE, {
fillColor: '#31708f'
});
delegate('click', '.carte.edit', event => {
const map = getCurrentMap(event.target);
if (map) {
const isPath = event.target.matches('.leaflet-container g path');
if (isPath) {
setTimeout(() => {
map.freeDraw.mode(FreeDraw.EDIT | FreeDraw.DELETE);
}, 50);
} else {
map.freeDraw.mode(FreeDraw.NONE);
}
}
});
delegate('click', '.toolbar .new-area', event => {
event.preventDefault();
const map = getCurrentMap(event.target);
if (map) {
map.freeDraw.mode(FreeDraw.CREATE);
}
});
$(document).on('select2:select', 'select[data-address]', event => {
const map = getCurrentMap(event.target);
const { geometry } = event.params.data;
if (map && geometry && geometry.type === 'Point') {
const [lon, lat] = geometry.coordinates;
map.setView(new L.LatLng(lat, lon), 14);
}
});
const USER_SELECTION_POLYGON_STYLE = {
color: 'red'
};

View file

@ -20,10 +20,9 @@
"highcharts": "^6.1.2",
"intersection-observer": "^0.7.0",
"jquery": "^3.4.1",
"leaflet": "^1.4.0",
"leaflet-freedraw": "^2.10.0",
"leaflet": "^1.6.0",
"leaflet-freedraw": "^2.12.0",
"prop-types": "^15.7.2",
"ramda": "=0.24.1",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-intersection-observer": "^8.25.2",