Improve map measurement tools and project layers

This commit is contained in:
livio committed 2026-09-21 12:01:35 +02:00
1 parent 0344227a1b
commit 06050b05f5
8 files changed
+396 -156

No files matched your search

+247 -67
View File
@@ -7,9 +7,12 @@ const lmeState = {
cadastreLayers: ["CP.CadastralParcel", "codice_plla", "CP.CadastralZoning", "fabbricati"],
cadastreOpacity: 0.75,
imported: null,
importedSheets: null,
importedSheetsVisible: false,
importedMeasurements: null,
drawings: null,
drawingMeasurements: null,
quickMeasureControl: null,
drawControl: null,
activeDrawHandler: null,
drawEventsBound: false,
@@ -52,6 +55,7 @@ window.lmeMap = {
fitImported,
clearImported,
setIncludeKmlSheetLayer,
setImportedSheetLayerVisible,
setImportedMeasurementsVisible,
setDrawingMeasurementsVisible,
addProjectMarker,
@@ -129,6 +133,7 @@ function init() {
lmeState.currentBase = lmeState.baseLayers.satellite.addTo(lmeState.map);
lmeState.imported = L.featureGroup().addTo(lmeState.map);
lmeState.importedSheets = L.featureGroup();
lmeState.drawings = L.featureGroup().addTo(lmeState.map);
lmeState.importedMeasurements = L.layerGroup().addTo(lmeState.map);
lmeState.drawingMeasurements = L.layerGroup().addTo(lmeState.map);
@@ -138,6 +143,8 @@ function init() {
refreshCadastreLayer();
bindFileImport();
bindDrawingEvents();
addQuickMeasureControl();
if (!lmeState.resizeBound) {
window.addEventListener("resize", resize);
@@ -183,21 +190,27 @@ function showSearchResult(latitude, longitude, label) {
setInfo(label || `${lat.toFixed(6)}, ${lon.toFixed(6)}`);
}
function showInitialPosition(location) {
const latitude = Number(location?.latitude);
const longitude = Number(location?.longitude);
const accuracy = Math.max(0, Number(location?.accuracy) || 0);
function showInitialPosition(latitudeValue, longitudeValue, approximate, label) {
const latitude = Number(latitudeValue);
const longitude = Number(longitudeValue);
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) {
return;
}
const latlng = [latitude, longitude];
lmeState.lastPosition = latlng;
lmeState.lastAccuracy = accuracy;
lmeState.map.setView(latlng, accuracy > 80 ? 17 : 19);
setText("gpsState", "Posizione iniziale acquisita - GPS non attivo");
setInfo("Mappa centrata sulla posizione attuale. GPS continuo non attivo.");
updateGpsInsideState();
if (!approximate) {
lmeState.lastPosition = latlng;
}
lmeState.map.setView(latlng, approximate ? 13 : 19);
setText("gpsState", approximate
? "Posizione approssimativa dalla connessione - GPS non attivo"
: "Posizione iniziale acquisita - GPS non attivo");
setInfo(approximate
? `Mappa centrata in modo approssimativo su ${label || "questa zona"}.`
: "Mappa centrata sulla posizione attuale. GPS continuo non attivo.");
if (!approximate) {
updateGpsInsideState();
}
}
function displayOfficialParcel(xmlText, latitude, longitude, parcel, label, shouldFit) {
@@ -457,7 +470,7 @@ function bindFileImport() {
try {
const result = await readGisFile(file);
const geojson = result.geojson;
const layer = L.geoJSON(geojson, {
const parcelLayer = L.geoJSON(geojson, {
style: { color: "#22c55e", weight: 3, opacity: 0.95, fillOpacity: 0.18 },
pointToLayer: (feature, latlng) => L.circleMarker(latlng, { radius: 7, color: "#22c55e", fillColor: "#ffffff", fillOpacity: 0.9 }),
onEachFeature: (feature, layer) => {
@@ -465,14 +478,28 @@ function bindFileImport() {
layer.bindPopup(`<strong>${escapeHtml(name)}</strong>`);
}
}).addTo(lmeState.imported);
fitLayer(layer);
const sheetGeojson = result.sheetGeojson || emptyFeatureCollection();
const sheetLayer = L.geoJSON(sheetGeojson, {
style: { color: "#15803d", weight: 3, opacity: 0.85, fillOpacity: 0.04, dashArray: "9 7" },
pointToLayer: (feature, latlng) => L.circleMarker(latlng, { radius: 6, color: "#15803d", fillOpacity: 0.25 }),
onEachFeature: (feature, layer) => {
const name = feature?.properties?.name || "Foglio catastale importato";
layer.bindPopup(`<strong>${escapeHtml(name)}</strong>`);
}
}).addTo(lmeState.importedSheets);
applyImportedSheetVisibility();
fitLayer(geojson.features.length ? parcelLayer : sheetLayer);
refreshImportedMeasurements();
const featureCount = geojson.features.length;
const sheetCount = sheetGeojson.features.length;
const ignored = result.ignoredCount
? `; esclusi ${result.ignoredCount} elementi del foglio o non particella`
: "";
const includedSheets = sheetCount
? `; ${sheetCount} elementi foglio ${lmeState.importedSheetsVisible ? "visibili" : "nascosti"}`
: "";
const reprojected = result.reprojected ? "; coordinate Web Mercator convertite" : "";
setInfo(`Caricato ${file.name}: ${featureCount} elementi${ignored}${reprojected}.`);
setInfo(`Caricato ${file.name}: ${featureCount} particelle/elementi${includedSheets}${ignored}${reprojected}.`);
updateGpsInsideState();
} catch (error) {
setInfo(`File non leggibile: ${error.message}`);
@@ -597,7 +624,12 @@ function normalizeGeoJson(value, fileName) {
}
delete root.crs;
return { geojson: root, ignoredCount: 0, reprojected: webMercator };
return {
geojson: root,
sheetGeojson: emptyFeatureCollection(),
ignoredCount: 0,
reprojected: webMercator
};
}
function isGeoJsonGeometry(value) {
@@ -675,13 +707,21 @@ function normalizeKmlFiles(files) {
}
const polygonParts = splitKmlPolygonFeatures(features);
const selected = lmeState.includeKmlSheetLayer ? features : filterKmlParcelFeatures(polygonParts);
if (!selected.length) {
throw new Error("nessuna particella trovata; attiva 'includi layer del foglio' per importare tutti gli elementi");
const parcels = filterKmlParcelFeatures(polygonParts);
const parcelSet = new Set(parcels);
const sheetParts = polygonParts.filter(feature => !parcelSet.has(feature));
const nonPolygonFeatures = features.filter(feature => geometryPolygons(feature.geometry).length === 0);
const optionalFeatures = [...sheetParts, ...nonPolygonFeatures];
if (!parcels.length && !(lmeState.includeKmlSheetLayer && optionalFeatures.length)) {
throw new Error("nessuna particella trovata; attiva 'includi layer del foglio' per importare gli altri elementi");
}
return {
geojson: { type: "FeatureCollection", features: selected },
ignoredCount: lmeState.includeKmlSheetLayer ? 0 : Math.max(0, polygonParts.length - selected.length),
geojson: { type: "FeatureCollection", features: parcels },
sheetGeojson: {
type: "FeatureCollection",
features: lmeState.includeKmlSheetLayer ? optionalFeatures : []
},
ignoredCount: lmeState.includeKmlSheetLayer ? 0 : optionalFeatures.length,
reprojected: false
};
}
@@ -724,10 +764,10 @@ function filterKmlParcelFeatures(features) {
.join(" ")
.toLowerCase();
const folder = String(properties._lmeFolder || "").toLowerCase();
const isParcel = /particell|mappal|parcel/.test(`${identity} ${folder}`)
|| /^[a-z]?\s*\d+[a-z]?(?:[\/. -]\d+[a-z]?)?$/i.test(name);
const isSheet = /\bfoglio\b|\bsheet\b|quadro[ _-]?d[' ]?unione|(?:perimetro|bordo|limite|contorno)[ _-]?(?:del[ _-]?)?foglio|sheet[ _-]?boundary/.test(identity);
return isParcel || !isSheet;
const context = `${identity} ${folder}`;
const hasParcelNumber = /^[a-z]?\s*\d+[a-z]?(?:[\/. -]\d+[a-z]?)?$/i.test(name);
const isSheet = /\bfoglio\b|\bsheet\b|quadro[ _-]?d[' ]?unione|(?:perimetro|bordo|limite|contorno)[ _-]?(?:del[ _-]?)?foglio|sheet[ _-]?boundary/.test(context);
return !isSheet || hasParcelNumber;
});
return removeLikelySheetOutlines(filtered);
}
@@ -837,6 +877,32 @@ function setIncludeKmlSheetLayer(enabled) {
: "Importazione KML/KMZ: verranno caricate solo le particelle riconosciute.");
}
function setImportedSheetLayerVisible(enabled) {
lmeState.importedSheetsVisible = Boolean(enabled);
applyImportedSheetVisibility();
const count = lmeState.importedSheets?.toGeoJSON()?.features?.length || 0;
setInfo(lmeState.importedSheetsVisible
? (count ? `Layer del foglio importato visibile (${count} elementi).` : "Il layer del foglio sara visibile quando verra importato.")
: "Layer del foglio importato nascosto; le particelle restano visibili.");
}
function applyImportedSheetVisibility() {
if (!lmeState.map || !lmeState.importedSheets) {
return;
}
if (lmeState.importedSheetsVisible) {
if (!lmeState.map.hasLayer(lmeState.importedSheets)) {
lmeState.importedSheets.addTo(lmeState.map);
}
lmeState.importedSheets.bringToBack();
lmeState.imported.bringToFront();
return;
}
if (lmeState.map.hasLayer(lmeState.importedSheets)) {
lmeState.map.removeLayer(lmeState.importedSheets);
}
}
function setImportedMeasurementsVisible(enabled) {
lmeState.showImportedMeasurements = Boolean(enabled);
refreshImportedMeasurements();
@@ -854,11 +920,18 @@ function setDrawingMeasurementsVisible(enabled) {
}
function fitImported() {
fitLayer(lmeState.imported);
const layers = [lmeState.imported];
if (lmeState.importedSheetsVisible) {
layers.push(lmeState.importedSheets);
}
fitLayer(L.featureGroup(layers));
}
function clearImported() {
lmeState.imported.clearLayers();
lmeState.importedSheets.clearLayers();
lmeState.importedSheetsVisible = false;
applyImportedSheetVisibility();
lmeState.importedMeasurements.clearLayers();
setInfo("File GIS rimossi.");
updateGpsInsideState();
@@ -877,6 +950,86 @@ function addProjectMarker(name) {
setInfo(`POI aggiunto: ${label}`);
}
function addQuickMeasureControl() {
if (!lmeState.map || lmeState.quickMeasureControl) {
return;
}
L.drawLocal.draw.toolbar.buttons.polygon = "Misura area";
L.drawLocal.draw.toolbar.buttons.polyline = "Misura distanza";
L.drawLocal.draw.toolbar.buttons.circle = "Misura cerchio";
L.drawLocal.draw.toolbar.buttons.rectangle = "Disegna rettangolo";
L.drawLocal.draw.toolbar.buttons.marker = "Aggiungi POI";
L.drawLocal.edit.toolbar.buttons.edit = "Modifica disegni";
L.drawLocal.edit.toolbar.buttons.remove = "Elimina disegni";
L.drawLocal.draw.handlers.polygon.tooltip.start = "Tocca il primo vertice dell'area.";
L.drawLocal.draw.handlers.polygon.tooltip.cont = "Tocca per aggiungere un vertice.";
L.drawLocal.draw.handlers.polygon.tooltip.end = "Tocca il primo punto per chiudere l'area.";
L.drawLocal.draw.handlers.polyline.tooltip.start = "Tocca il primo punto della distanza.";
L.drawLocal.draw.handlers.polyline.tooltip.cont = "Tocca per aggiungere un tratto.";
L.drawLocal.draw.handlers.polyline.tooltip.end = "Tocca l'ultimo punto per terminare.";
L.drawLocal.draw.handlers.circle.tooltip.start = "Tocca il centro e trascina per il raggio.";
const orangeArea = { color: "#f97316", weight: 4, fillColor: "#fb923c", fillOpacity: 0.2 };
lmeState.quickMeasureControl = new L.Control.Draw({
position: "topright",
edit: false,
draw: {
circle: { metric: true, feet: false, showRadius: true, shapeOptions: orangeArea },
circlemarker: false,
marker: false,
polygon: {
metric: true,
feet: false,
showArea: true,
allowIntersection: false,
shapeOptions: orangeArea
},
polyline: {
metric: true,
feet: false,
showLength: true,
shapeOptions: { color: "#f97316", weight: 4, opacity: 0.95 }
},
rectangle: false
}
});
lmeState.map.addControl(lmeState.quickMeasureControl);
}
function bindDrawingEvents() {
if (!lmeState.map || lmeState.drawEventsBound) {
return;
}
lmeState.map.on(L.Draw.Event.CREATED, event => {
annotateDrawingLayer(event.layer, event.layerType);
lmeState.drawings.addLayer(event.layer);
refreshDrawingMeasurements();
updateGpsInsideState();
const completedLabels = {
polygon: "Area completata: superficie, perimetro e lati aggiornati.",
rectangle: "Rettangolo completato: superficie, perimetro e lati aggiornati.",
polyline: "Distanza completata: lunghezza totale e tratti aggiornati.",
circle: "Cerchio completato: superficie, raggio e circonferenza aggiornati.",
marker: "Punto aggiunto alla mappa."
};
setInfo(completedLabels[event.layerType] || "Disegno completato.");
});
lmeState.map.on(L.Draw.Event.EDITED, event => {
event.layers.eachLayer(layer => annotateDrawingLayer(layer));
refreshDrawingMeasurements();
updateGpsInsideState();
});
lmeState.map.on(L.Draw.Event.DELETED, () => {
refreshDrawingMeasurements();
updateGpsInsideState();
});
lmeState.map.on(L.Draw.Event.DRAWSTOP, () => {
lmeState.activeDrawHandler = null;
});
lmeState.drawEventsBound = true;
}
function enableDrawTools() {
if (lmeState.drawControl) {
setInfo("Strumenti di disegno gia attivi.");
@@ -887,55 +1040,24 @@ function enableDrawTools() {
position: "topright",
edit: { featureGroup: lmeState.drawings },
draw: {
circle: { metric: true, feet: false },
circle: false,
circlemarker: false,
marker: true,
polygon: { metric: true, feet: false, showArea: true, allowIntersection: false },
polyline: { metric: true, feet: false, showLength: true },
rectangle: true
polygon: false,
polyline: false,
rectangle: { metric: true, shapeOptions: { color: "#f97316", weight: 4, fillOpacity: 0.2 } }
}
});
lmeState.map.addControl(lmeState.drawControl);
if (!lmeState.drawEventsBound) {
lmeState.map.on(L.Draw.Event.CREATED, event => {
annotateDrawingLayer(event.layer, event.layerType);
lmeState.drawings.addLayer(event.layer);
refreshDrawingMeasurements();
updateGpsInsideState();
const completedLabels = {
polygon: "Area completata: superficie, perimetro e lati aggiornati.",
rectangle: "Rettangolo completato: superficie, perimetro e lati aggiornati.",
polyline: "Distanza completata: lunghezza totale e tratti aggiornati.",
circle: "Cerchio completato: superficie, raggio e circonferenza aggiornati.",
marker: "Punto aggiunto alla mappa."
};
setInfo(completedLabels[event.layerType] || "Disegno completato.");
});
lmeState.map.on(L.Draw.Event.EDITED, event => {
event.layers.eachLayer(layer => annotateDrawingLayer(layer));
refreshDrawingMeasurements();
updateGpsInsideState();
});
lmeState.map.on(L.Draw.Event.DELETED, () => {
refreshDrawingMeasurements();
updateGpsInsideState();
});
lmeState.map.on(L.Draw.Event.DRAWSTOP, () => {
lmeState.activeDrawHandler = null;
});
lmeState.drawEventsBound = true;
}
setInfo("Disegno attivo: crea POI, linee e aree sulla mappa.");
bindDrawingEvents();
setInfo("Barra completa attiva: rettangolo, POI, modifica e cancellazione.");
}
function startMeasurementDrawing(mode) {
if (!lmeState.map) {
return;
}
if (!lmeState.drawEventsBound) {
enableDrawTools();
setDrawToolsVisible(false);
}
bindDrawingEvents();
if (lmeState.activeDrawHandler) {
lmeState.activeDrawHandler.disable();
}
@@ -1255,7 +1377,7 @@ function formatNumber(value, digits) {
function createProjectSnapshot(includeCadastralParcels) {
const center = lmeState.map.getCenter();
return JSON.stringify({
schemaVersion: 1,
schemaVersion: 2,
view: {
latitude: center.lat,
longitude: center.lng,
@@ -1263,6 +1385,8 @@ function createProjectSnapshot(includeCadastralParcels) {
},
drawings: lmeState.drawings.toGeoJSON(),
imported: lmeState.imported.toGeoJSON(),
importedSheets: lmeState.importedSheets.toGeoJSON(),
importedSheetsVisible: lmeState.importedSheetsVisible,
selectedParcels: includeCadastralParcels
? lmeState.selectedParcelsLayer.toGeoJSON()
: { type: "FeatureCollection", features: [] },
@@ -1290,6 +1414,7 @@ function loadProjectSnapshot(raw, projectName) {
lmeState.drawings.clearLayers();
lmeState.imported.clearLayers();
lmeState.importedSheets.clearLayers();
lmeState.drawingMeasurements.clearLayers();
lmeState.importedMeasurements.clearLayers();
lmeState.selectedParcelsLayer.clearLayers();
@@ -1313,7 +1438,10 @@ function loadProjectSnapshot(raw, projectName) {
onEachFeature: bindStoredFeaturePopup
});
restoredDrawings.eachLayer(layer => lmeState.drawings.addLayer(layer));
L.geoJSON(data.imported || emptyFeatureCollection(), {
const importedParts = partitionStoredImportedFeatures(
data.imported || emptyFeatureCollection(),
data.importedSheets || emptyFeatureCollection());
L.geoJSON(importedParts.parcels, {
style: { color: "#22c55e", weight: 3, opacity: 0.95, fillOpacity: 0.18 },
pointToLayer: (feature, latlng) => L.circleMarker(latlng, {
radius: 7,
@@ -1323,6 +1451,17 @@ function loadProjectSnapshot(raw, projectName) {
}),
onEachFeature: bindStoredFeaturePopup
}).addTo(lmeState.imported);
L.geoJSON(importedParts.sheets, {
style: { color: "#15803d", weight: 3, opacity: 0.85, fillOpacity: 0.04, dashArray: "9 7" },
pointToLayer: (feature, latlng) => L.circleMarker(latlng, {
radius: 6,
color: "#15803d",
fillOpacity: 0.25
}),
onEachFeature: bindStoredFeaturePopup
}).addTo(lmeState.importedSheets);
lmeState.importedSheetsVisible = data.schemaVersion >= 2 && Boolean(data.importedSheetsVisible);
applyImportedSheetVisibility();
L.geoJSON(data.selectedParcels || emptyFeatureCollection(), {
style: { color: "#ef4444", weight: 4, opacity: 1, fillColor: "#fbbf24", fillOpacity: 0.26 },
onEachFeature: (feature, layer) => {
@@ -1341,12 +1480,16 @@ function loadProjectSnapshot(raw, projectName) {
refreshImportedMeasurements();
refreshDrawingMeasurements();
const projectLayers = L.featureGroup([
const projectLayerList = [
lmeState.drawings,
lmeState.imported,
lmeState.selectedParcelsLayer,
lmeState.gpsTrail
]);
];
if (lmeState.importedSheetsVisible) {
projectLayerList.push(lmeState.importedSheets);
}
const projectLayers = L.featureGroup(projectLayerList);
if (projectLayers.getBounds().isValid()) {
fitLayer(projectLayers);
} else if (Number.isFinite(data.view?.latitude)
@@ -1360,13 +1503,48 @@ function loadProjectSnapshot(raw, projectName) {
? `${parcelCount} particelle del progetto`
: "Nessuna particella selezionata");
updateGpsInsideState();
setInfo(`Progetto caricato: ${projectName || "senza nome"}.`);
const hiddenSheets = importedParts.sheets.features.length && !lmeState.importedSheetsVisible
? ` ${importedParts.sheets.features.length} elementi del foglio sono nascosti.`
: "";
setInfo(`Progetto caricato: ${projectName || "senza nome"}.${hiddenSheets}`);
return lmeState.importedSheetsVisible;
} catch (error) {
setInfo(`Progetto non leggibile: ${error.message}`);
throw error;
}
}
function partitionStoredImportedFeatures(imported, storedSheets) {
const parcelFeatures = [];
const sheetFeatures = [...(storedSheets?.features || [])];
const sourceGroups = new Map();
(imported?.features || []).forEach(feature => {
const source = String(feature?.properties?._lmeSource || "");
if (!/\.(kml|kmz)$/i.test(source)) {
parcelFeatures.push(feature);
return;
}
const group = sourceGroups.get(source) || [];
group.push(feature);
sourceGroups.set(source, group);
});
sourceGroups.forEach(features => {
const polygonParts = splitKmlPolygonFeatures(features);
const parcels = filterKmlParcelFeatures(polygonParts);
const parcelSet = new Set(parcels);
parcelFeatures.push(...parcels);
sheetFeatures.push(...polygonParts.filter(feature => !parcelSet.has(feature)));
sheetFeatures.push(...features.filter(feature => geometryPolygons(feature.geometry).length === 0));
});
return {
parcels: { type: "FeatureCollection", features: parcelFeatures },
sheets: { type: "FeatureCollection", features: sheetFeatures }
};
}
function emptyFeatureCollection() {
return { type: "FeatureCollection", features: [] };
}
@@ -1661,6 +1839,7 @@ function clearMapElements() {
const count = lmeState.selectedParcelsLayer.getLayers().length
+ lmeState.gpsParcelLayer.getLayers().length
+ lmeState.imported.getLayers().length
+ lmeState.importedSheets.getLayers().length
+ lmeState.drawings.getLayers().length
+ lmeState.gpsTrailPoints.length;
if (!count) {
@@ -1674,6 +1853,7 @@ function clearMapElements() {
lmeState.selectedParcelsLayer.clearLayers();
lmeState.gpsParcelLayer.clearLayers();
lmeState.imported.clearLayers();
lmeState.importedSheets.clearLayers();
lmeState.drawings.clearLayers();
lmeState.importedMeasurements.clearLayers();
lmeState.drawingMeasurements.clearLayers();