Compare commits

..
3 Commits
Author SHA1 Message Date
livio 0344227a1b Center map on startup location 2026-09-21 11:24:22 +02:00
livio 7933b2e86a Reorganize map tools and improve KML sheet filtering 2026-09-21 11:01:12 +02:00
livio c8b8f21d8d Improve GIS import and add measurement tools 2026-09-21 09:31:35 +02:00
7 changed files with 1197 additions and 132 deletions

No files matched your search

+223 -96
View File
@@ -72,6 +72,16 @@
<button class="gps-center" @onclick="CenterOnGps" aria-label="Centra posizione">Centra</button>
</div>
@if ((ActiveTab is "map" or "search") && !LayerPanelOpen)
{
<div class="map-measure-tools @(ActiveTab == "search" ? "search-open" : null)" aria-label="Strumenti rapidi di misura">
<span>Misura</span>
<button title="Disegna e misura un'area" @onclick='() => StartMeasurementDrawing("area")'>Area</button>
<button title="Disegna e misura una distanza" @onclick='() => StartMeasurementDrawing("distance")'>Distanza</button>
<button title="Disegna e misura un cerchio" @onclick='() => StartMeasurementDrawing("circle")'>Cerchio</button>
</div>
}
@if (ActiveTab is not "map" and not "search")
{
<aside class="tool-sheet">
@@ -149,111 +159,159 @@
</div>
</section>
}
else if (ActiveTab == "data")
{
<section class="panel-content">
<section class="panel-section">
<h2>File GIS</h2>
<label class="file-picker">
<span>Carica KML, KMZ o GeoJSON</span>
<input id="gisFileInput" type="file" accept=".kml,.kmz,.geojson,.json,application/vnd.google-earth.kml+xml,application/vnd.google-earth.kmz,application/geo+json" />
</label>
<label class="toggle-line project-save-option">
<input type="checkbox" checked="@IncludeKmlSheetLayer" @onchange="ToggleKmlSheetLayer" />
<span>KML/KMZ: includi anche il layer del foglio</span>
</label>
<small class="field-help">
@(IncludeKmlSheetLayer
? "Attivato: importa foglio, particelle e altri elementi KML/KMZ."
: "Disattivato: importa solo i poligoni delle particelle riconosciute.")
</small>
<label class="toggle-line project-save-option">
<input type="checkbox" checked="@ShowImportedMeasurements" @onchange="ToggleImportedMeasurements" />
<span>Mostra misure dei file caricati</span>
</label>
<div class="button-row">
<button @onclick="FitImportedLayers">Inquadra dati</button>
<button class="secondary-command" @onclick="ClearImportedLayers">Rimuovi dati</button>
</div>
</section>
<section class="panel-section">
<h2>Disegni e misure</h2>
<label class="toggle-line project-save-option">
<input type="checkbox" checked="@ShowDrawingMeasurements" @onchange="ToggleDrawingMeasurements" />
<span>Mostra superficie, perimetro e lati</span>
</label>
<button class="secondary-command" aria-pressed="@DrawToolsVisible" @onclick="ToggleDrawTools">
@(DrawToolsVisible ? "Nascondi barra completa" : "Mostra barra completa")
</button>
<button class="danger-command" @onclick="ClearDrawings">Elimina disegni e POI</button>
</section>
<section class="panel-section">
<h2>Punti di interesse</h2>
<label>
Nome POI
<input @bind="PoiName" @bind:event="oninput" placeholder="Nome del punto" />
</label>
<button class="primary-command" @onclick="AddProjectMarker">Aggiungi POI al centro mappa</button>
</section>
</section>
}
else if (ActiveTab == "projects")
{
<section class="panel-content">
<h2>File GIS</h2>
<label class="file-picker">
<span>Carica KML, KMZ o GeoJSON</span>
<input id="gisFileInput" type="file" accept=".kml,.kmz,.geojson,.json,application/vnd.google-earth.kml+xml,application/vnd.google-earth.kmz,application/geo+json" />
</label>
<div class="button-row">
<button @onclick="FitImportedLayers">Inquadra</button>
<button class="secondary-command" @onclick="ClearImportedLayers">Pulisci</button>
</div>
<section class="panel-section">
<h2>Salva progetto</h2>
<label>
Nome progetto
<input @bind="NewProjectName" @bind:event="oninput" placeholder="Es. Rilievo San Nicola" maxlength="80" />
</label>
<label class="toggle-line project-save-option">
<input type="checkbox" @bind="IncludeCadastralParcels" />
<span>Includi le particelle catastali rosse</span>
</label>
<button class="primary-command" @onclick="SaveProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(NewProjectName))">Salva progetto</button>
</section>
<h2>Archivio progetti</h2>
<label>
Nome progetto
<input @bind="NewProjectName" @bind:event="oninput" placeholder="Es. Rilievo San Nicola" maxlength="80" />
</label>
<label class="toggle-line project-save-option">
<input type="checkbox" @bind="IncludeCadastralParcels" />
<span>Includi le particelle catastali rosse</span>
</label>
<button class="primary-command" @onclick="SaveProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(NewProjectName))">Salva progetto</button>
<label>
Progetto salvato
<select value="@SelectedProjectId" @onchange="SelectProject" disabled="@(Projects.Count == 0 || ProjectBusy)">
<option value="">Seleziona un progetto</option>
@foreach (var project in Projects)
{
<option value="@project.Id">@project.Name - @project.UpdatedAt.ToLocalTime().ToString("dd/MM/yyyy HH:mm")</option>
}
</select>
</label>
<div class="button-row">
<button @onclick="LoadProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Carica</button>
<button class="danger-command" @onclick="DeleteProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Elimina</button>
</div>
<div class="project-archive-state">@ProjectArchiveMessage</div>
<h2>POI e disegni</h2>
<label>
Nome POI
<input @bind="PoiName" @bind:event="oninput" placeholder="Nome del punto" />
</label>
<button class="primary-command" @onclick="AddProjectMarker">Aggiungi POI al centro mappa</button>
<button class="secondary-command" aria-pressed="@DrawToolsVisible" @onclick="ToggleDrawTools">
@(DrawToolsVisible ? "Nascondi strumenti di disegno" : "Mostra strumenti di disegno")
</button>
<button class="danger-command" @onclick="ClearDrawings">Elimina disegni e POI</button>
<section class="panel-section">
<h2>Apri progetto</h2>
<label>
Progetto salvato
<select value="@SelectedProjectId" @onchange="SelectProject" disabled="@(Projects.Count == 0 || ProjectBusy)">
<option value="">Seleziona un progetto</option>
@foreach (var project in Projects)
{
<option value="@project.Id">@project.Name - @project.UpdatedAt.ToLocalTime().ToString("dd/MM/yyyy HH:mm")</option>
}
</select>
</label>
<div class="button-row">
<button @onclick="LoadProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Apri</button>
<button class="danger-command" @onclick="DeleteProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Elimina</button>
</div>
<div class="project-archive-state">@ProjectArchiveMessage</div>
</section>
</section>
}
else if (ActiveTab == "settings")
{
<section class="panel-content">
<h2>Visualizzazione</h2>
<label>
Sfondo
<select value="@SelectedBaseLayer" @onchange="ChangeBaseLayer">
<option value="satellite">Satellite - Esri World Imagery</option>
<option value="osm">Strade - OpenStreetMap</option>
<option value="streets-esri">Strade dettagliate - Esri World Street Map</option>
<option value="topographic">Topografica - Esri World Topographic</option>
<option value="terrain">Terreno - OpenTopoMap</option>
<option value="carto">Strade chiare - CARTO Voyager</option>
<option value="azure-road">Strade - Azure Maps</option>
<option value="azure-satellite">Satellite - Azure Maps</option>
<option value="google-satellite">Satellite - Google Maps</option>
<option value="google-roadmap">Strade - Google Maps</option>
</select>
</label>
<label>
Chiave Google Maps Platform
<input type="password" @bind="GoogleMapsApiKey" placeholder="API key" autocomplete="off" />
</label>
<button class="secondary-command" @onclick="SaveGoogleMapsApiKey">Salva chiave Google</button>
<label>
Chiave sottoscrizione Azure Maps Gen2
<input type="password" @bind="AzureMapsSubscriptionKey" placeholder="Subscription key" autocomplete="off" />
</label>
<button class="secondary-command" @onclick="SaveAzureMapsKey">Salva chiave Azure Maps</button>
<div class="service-note">
<strong>Quota gratuita Azure Maps Gen2</strong>
<p>Include ogni mese 5.000 transazioni per le mappe stradali e 1.000 per le immagini satellitari. Ogni transazione comprende fino a 15 tessere.</p>
</div>
<label>
Trasparenza catasto
<input type="range" min="0" max="1" step="0.05" value="0.75" @onchange="ChangeCadastreOpacity" />
</label>
<h2>GPS e percorso</h2>
<label class="toggle-line">
<input type="checkbox" checked="@TrailEnabled" @onchange="ToggleTrail" />
Registra la traccia mentre cammini
</label>
<section class="panel-section">
<h2>Mappa e sfondo</h2>
<label>
Sfondo
<select value="@SelectedBaseLayer" @onchange="ChangeBaseLayer">
<option value="satellite">Satellite - Esri World Imagery</option>
<option value="osm">Strade - OpenStreetMap</option>
<option value="streets-esri">Strade dettagliate - Esri World Street Map</option>
<option value="topographic">Topografica - Esri World Topographic</option>
<option value="terrain">Terreno - OpenTopoMap</option>
<option value="carto">Strade chiare - CARTO Voyager</option>
<option value="azure-road">Strade - Azure Maps</option>
<option value="azure-satellite">Satellite - Azure Maps</option>
<option value="google-satellite">Satellite - Google Maps</option>
<option value="google-roadmap">Strade - Google Maps</option>
</select>
</label>
<label>
Trasparenza catasto
<input type="range" min="0" max="1" step="0.05" value="0.75" @onchange="ChangeCadastreOpacity" />
</label>
</section>
<h2>Servizi Agenzia delle Entrate</h2>
<div class="service-note protected-service">
<strong>Download documenti e fogli ufficiali</strong>
<p>Il CAPTCHA o l'accesso SPID/CIE vengono gestiti direttamente dal sito dell'Agenzia. Per sicurezza l'app non tenta di aggirarli.</p>
<button class="primary-command" @onclick="OpenOfficialGeoportal">Apri Geoportale catastale</button>
<button class="secondary-command" @onclick="OpenOfficialReservedArea">Apri Area riservata per download</button>
</div>
<section class="panel-section">
<h2>Servizi mappa con chiave</h2>
<label>
Chiave Google Maps Platform
<input type="password" @bind="GoogleMapsApiKey" placeholder="API key" autocomplete="off" />
</label>
<button class="secondary-command" @onclick="SaveGoogleMapsApiKey">Salva chiave Google</button>
<label>
Chiave sottoscrizione Azure Maps Gen2
<input type="password" @bind="AzureMapsSubscriptionKey" placeholder="Subscription key" autocomplete="off" />
</label>
<button class="secondary-command" @onclick="SaveAzureMapsKey">Salva chiave Azure Maps</button>
<div class="service-note">
<strong>Quota gratuita Azure Maps Gen2</strong>
<p>Include ogni mese 5.000 transazioni per le mappe stradali e 1.000 per le immagini satellitari. Ogni transazione comprende fino a 15 tessere.</p>
</div>
</section>
<button class="secondary-command" @onclick="ExportCadastralImage">Mostra vista WMS corrente</button>
<footer>Dati catastali: Agenzia delle Entrate, licenza CC BY 4.0. App indipendente.</footer>
<section class="panel-section">
<h2>GPS e percorso</h2>
<label class="toggle-line project-save-option">
<input type="checkbox" checked="@ShowGpsPosition" @onchange="ToggleGpsPosition" />
<span>Mostra punto e cerchio GPS</span>
</label>
<label class="toggle-line project-save-option">
<input type="checkbox" checked="@TrailEnabled" @onchange="ToggleTrail" />
<span>Registra la traccia mentre cammini</span>
</label>
</section>
<section class="panel-section">
<h2>Servizi Agenzia delle Entrate</h2>
<div class="service-note protected-service">
<strong>Download documenti e fogli ufficiali</strong>
<p>Il CAPTCHA o l'accesso SPID/CIE vengono gestiti direttamente dal sito dell'Agenzia. Per sicurezza l'app non tenta di aggirarli.</p>
<button class="primary-command" @onclick="OpenOfficialGeoportal">Apri Geoportale catastale</button>
<button class="secondary-command" @onclick="OpenOfficialReservedArea">Apri Area riservata per download</button>
</div>
<button class="secondary-command" @onclick="ExportCadastralImage">Mostra vista WMS corrente</button>
<footer>Dati catastali: Agenzia delle Entrate, licenza CC BY 4.0. App indipendente.</footer>
</section>
</section>
}
</aside>
@@ -283,6 +341,7 @@
<nav class="bottom-tabs" aria-label="Sezioni principali">
<button class="@(ActiveTab == "map" || ActiveTab == "search" ? "active" : null)" @onclick='() => SelectTab("map")'>Mappa</button>
<button class="@(ActiveTab == "cadastre" ? "active" : null)" @onclick='() => SelectTab("cadastre")'>Catasto</button>
<button class="@(ActiveTab == "data" ? "active" : null)" @onclick='() => SelectTab("data")'>Dati</button>
<button class="@(ActiveTab == "projects" ? "active" : null)" @onclick='() => SelectTab("projects")'>Progetti</button>
<button class="@(ActiveTab == "settings" ? "active" : null)" @onclick='() => SelectTab("settings")'>Impostazioni</button>
</nav>
@@ -308,10 +367,14 @@
private double? CatalogFraction { get; set; }
private bool CatalogBusy { get; set; }
private bool GpsActive { get; set; }
private bool ShowGpsPosition { get; set; } = true;
private bool DrawToolsVisible { get; set; }
private bool TrailEnabled { get; set; }
private bool LayerPanelOpen { get; set; }
private bool IncludeCadastralParcels { get; set; } = true;
private bool IncludeKmlSheetLayer { get; set; }
private bool ShowImportedMeasurements { get; set; }
private bool ShowDrawingMeasurements { get; set; } = true;
private bool ProjectBusy { get; set; }
private CancellationTokenSource? CatalogCancellation { get; set; }
private CancellationTokenSource? GpsLookupCancellation { get; set; }
@@ -333,7 +396,8 @@
private string PanelTitle => ActiveTab switch
{
"cadastre" => "Ricerca catastale",
"projects" => "Progetti e dati",
"data" => "Dati e disegni",
"projects" => "Archivio progetti",
"settings" => "Impostazioni",
_ => string.Empty
};
@@ -341,7 +405,8 @@
private string PanelEyebrow => ActiveTab switch
{
"cadastre" => "Regione, Comune, Foglio, Particella",
"projects" => "KML, KMZ, GeoJSON e POI",
"data" => "File GIS, misure e POI",
"projects" => "Salva e apri i tuoi lavori",
"settings" => "Mappa, GPS e servizi ufficiali",
_ => string.Empty
};
@@ -393,10 +458,36 @@
if (firstRender)
{
await JS.InvokeVoidAsync("lmeMap.init");
await CenterOnInitialLocationAsync();
await MigrateLegacyProjectAsync();
}
}
private async Task CenterOnInitialLocationAsync()
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(12));
try
{
var location = await LocationService.GetCurrentLocationAsync(timeout.Token);
if (location is not null)
{
await JS.InvokeVoidAsync("lmeMap.showInitialPosition", location);
}
else
{
await JS.InvokeVoidAsync("lmeMap.showInfo", "Posizione iniziale non disponibile. La mappa resta utilizzabile normalmente.");
}
}
catch (OperationCanceledException)
{
await JS.InvokeVoidAsync("lmeMap.showInfo", "Ricerca della posizione iniziale scaduta. Usa Avvia GPS per riprovare.");
}
catch (Exception error)
{
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Posizione iniziale non disponibile: {error.GetBaseException().Message}");
}
}
private async Task MigrateLegacyProjectAsync()
{
try
@@ -620,6 +711,12 @@
}
}
private async Task ToggleGpsPosition(ChangeEventArgs args)
{
ShowGpsPosition = (bool?)args.Value == true;
await JS.InvokeVoidAsync("lmeMap.setGpsPositionVisible", ShowGpsPosition);
}
private async Task StartGps()
{
GpsActive = true;
@@ -728,6 +825,36 @@
private Task FitImportedLayers() => JS.InvokeVoidAsync("lmeMap.fitImported").AsTask();
private Task ClearImportedLayers() => JS.InvokeVoidAsync("lmeMap.clearImported").AsTask();
private Task AddProjectMarker() => JS.InvokeVoidAsync("lmeMap.addProjectMarker", PoiName).AsTask();
private async Task ToggleKmlSheetLayer(ChangeEventArgs args)
{
IncludeKmlSheetLayer = (bool?)args.Value == true;
await JS.InvokeVoidAsync("lmeMap.setIncludeKmlSheetLayer", IncludeKmlSheetLayer);
}
private async Task ToggleImportedMeasurements(ChangeEventArgs args)
{
ShowImportedMeasurements = (bool?)args.Value == true;
await JS.InvokeVoidAsync("lmeMap.setImportedMeasurementsVisible", ShowImportedMeasurements);
}
private async Task ToggleDrawingMeasurements(ChangeEventArgs args)
{
ShowDrawingMeasurements = (bool?)args.Value == true;
await JS.InvokeVoidAsync("lmeMap.setDrawingMeasurementsVisible", ShowDrawingMeasurements);
}
private async Task StartMeasurementDrawing(string mode)
{
DrawToolsVisible = false;
await JS.InvokeVoidAsync("lmeMap.setDrawToolsVisible", false);
ActiveTab = "map";
LayerPanelOpen = false;
await Task.Delay(30);
await JS.InvokeVoidAsync("lmeMap.resize");
await JS.InvokeVoidAsync("lmeMap.startMeasurementDrawing", mode);
}
private async Task ToggleDrawTools()
{
DrawToolsVisible = !DrawToolsVisible;
+2 -2
View File
@@ -28,8 +28,8 @@
<ApplicationId>com.companyname.lmemappecatastaliapp</ApplicationId>
<!-- Versions -->
<ApplicationDisplayVersion>0.2.7</ApplicationDisplayVersion>
<ApplicationVersion>11</ApplicationVersion>
<ApplicationDisplayVersion>0.2.10</ApplicationDisplayVersion>
<ApplicationVersion>14</ApplicationVersion>
<!-- To develop, package, and publish an app to the Microsoft Store, see: https://aka.ms/MauiTemplateUnpackaged -->
<WindowsPackageType>None</WindowsPackageType>
+7 -1
View File
@@ -9,16 +9,22 @@ App .NET MAUI Blazor Hybrid per Android, iOS, Mac Catalyst e Windows, pensata pe
- Trasparenza configurabile del layer catastale.
- Interrogazione WMS con click/tap sulla mappa.
- Import di file KML, KMZ, GeoJSON e JSON.
- Import GeoJSON compatibile con BOM, geometrie singole, array, FeatureCollection e coordinate Web Mercator EPSG:3857.
- Filtro KML/KMZ `solo particelle` attivo per impostazione predefinita, con separazione dei MultiPolygon ed esclusione di GroundOverlay e perimetri del foglio; il layer foglio resta importabile tramite opzione.
- Inquadramento e pulizia dei layer importati.
- Disegno di marker, linee, poligoni e rettangoli.
- Modalita rapide Area, Distanza e Cerchio disponibili direttamente sulla mappa, con superficie, perimetro, raggio, circonferenza e lunghezza dei singoli lati.
- Misure permanenti attivabili anche sui layer importati da KML, KMZ e GeoJSON.
- Toolbar di disegno completa di icone, modifica, eliminazione singola e pulizia di tutti i disegni/POI.
- Archivio multiprogetto nella cartella privata dell'app, con nome, selezione da elenco, sovrascrittura ed eliminazione.
- Ogni progetto salva file GIS, POI, disegni, traccia e inquadratura; l'inclusione delle particelle catastali rosse e' opzionale.
- GPS nativo MAUI ad alta precisione con permessi Android/iOS.
- Centratura automatica una tantum sulla posizione attuale all'apertura, senza mostrare il punto o il cerchio e senza avviare il tracking GPS continuo.
- Punto e cerchio di precisione del GPS live possono essere mostrati o nascosti dalle impostazioni senza fermare il rilevamento.
- Marker posizione, cerchio accuratezza in metri, tracciamento percorso.
- Controllo se la posizione GPS cade dentro un poligono importato o disegnato.
- Interrogazione WFS ufficiale Agenzia delle Entrate attorno alla posizione GPS per evidenziare la particella catastale corrente quando il servizio restituisce la geometria.
- Mappa a tutto schermo con tab Catasto, Progetti e Impostazioni, adattabile agli schermi pieghevoli.
- Mappa a tutto schermo con tab separati Catasto, Dati, Progetti e Impostazioni, adattabile agli schermi pieghevoli.
- Ingrandimento oltre lo zoom satellitare nativo senza tessere "Map data not yet available".
- Tendine concatenate Regione, Comune, Foglio e Particella.
- Ricerca di localita e indirizzi eseguita nativamente con fallback Esri e OpenStreetMap, senza richieste CORS dalla WebView.
+1 -1
View File
@@ -13,7 +13,7 @@ public sealed class AzureMapsService
public AzureMapsService()
{
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LMEMappeCatastali/0.2.7");
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LMEMappeCatastali/0.2.10");
_httpClient.DefaultRequestHeaders.Accept.ParseAdd("application/json");
}
+41 -8
View File
@@ -20,6 +20,37 @@ public sealed class PreciseLocationService : IAsyncDisposable
return status;
}
public async Task<LocationSnapshot?> GetCurrentLocationAsync(CancellationToken cancellationToken = default)
{
var permission = await EnsurePermissionAsync();
if (permission != PermissionStatus.Granted)
{
return null;
}
Location? location = null;
try
{
var request = new GeolocationRequest(GeolocationAccuracy.Best, TimeSpan.FromSeconds(8));
location = await Geolocation.Default.GetLocationAsync(request, cancellationToken);
}
catch (FeatureNotSupportedException)
{
return null;
}
if (location is null)
{
var lastKnown = await Geolocation.Default.GetLastKnownLocationAsync();
if (lastKnown is not null && lastKnown.Timestamp >= DateTimeOffset.UtcNow.AddMinutes(-15))
{
location = lastKnown;
}
}
return location is null ? null : ToSnapshot(location);
}
public async Task StartTrackingAsync(Func<LocationSnapshot, Task> onLocation, Func<string, Task> onError)
{
if (trackingCancellation is not null)
@@ -47,14 +78,7 @@ public sealed class PreciseLocationService : IAsyncDisposable
var location = await Geolocation.Default.GetLocationAsync(request, token);
if (location is not null)
{
await onLocation(new LocationSnapshot(
location.Latitude,
location.Longitude,
location.Accuracy,
location.Altitude,
location.Course,
location.Speed,
location.Timestamp));
await onLocation(ToSnapshot(location));
}
}
catch (OperationCanceledException)
@@ -84,6 +108,15 @@ public sealed class PreciseLocationService : IAsyncDisposable
StopTracking();
return ValueTask.CompletedTask;
}
private static LocationSnapshot ToSnapshot(Location location) => new(
location.Latitude,
location.Longitude,
location.Accuracy,
location.Altitude,
location.Course,
location.Speed,
location.Timestamp);
}
public sealed record LocationSnapshot(
+137 -1
View File
@@ -292,6 +292,43 @@ input[type="checkbox"] {
color: var(--ink);
}
.map-measure-tools {
position: absolute;
top: 72px;
right: 12px;
z-index: 860;
display: grid;
grid-template-columns: auto repeat(3, minmax(76px, auto));
align-items: center;
gap: 6px;
padding: 7px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 8px;
background: rgba(255, 255, 255, 0.96);
box-shadow: 0 3px 14px rgba(0, 0, 0, 0.2);
transition: top 140ms ease;
}
.map-measure-tools > span {
padding: 0 4px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
}
.map-measure-tools button {
min-height: 38px;
padding: 0 10px;
background: #fff3e8;
color: #8a3a08;
border: 1px solid #e4b58f;
}
.map-measure-tools.search-open {
top: 140px;
}
.tool-sheet {
position: absolute;
top: 0;
@@ -358,6 +395,29 @@ h2 {
padding: 15px 16px 24px;
}
.panel-section {
display: grid;
gap: 12px;
padding: 0 0 16px;
border-bottom: 1px solid var(--line);
}
.panel-section:last-child {
padding-bottom: 0;
border-bottom: 0;
}
.panel-section h2 {
margin-top: 0;
}
.field-help {
margin-top: -7px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
label {
display: grid;
gap: 5px;
@@ -472,6 +532,56 @@ label {
line-height: 1.35;
}
.measurement-mode-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 7px;
}
.measurement-mode-grid button {
min-width: 0;
padding: 0 8px;
}
.lme-measure-label {
width: 0 !important;
height: 0 !important;
border: 0 !important;
background: transparent !important;
pointer-events: none !important;
}
.lme-measure-label span {
position: absolute;
transform: translate(-50%, -50%);
border: 1px solid rgba(23, 33, 43, 0.35);
border-radius: 4px;
padding: 2px 5px;
background: rgba(255, 255, 255, 0.92);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.24);
color: #17212b;
font-size: 10px;
font-weight: 800;
line-height: 1.25;
white-space: nowrap;
}
.lme-measure-label.imported span {
border-color: #15806a;
color: #0c5749;
}
.lme-measure-label.drawing span {
border-color: #d35d0b;
color: #7c2d12;
}
.lme-measure-label.side span {
padding: 1px 4px;
font-size: 9px;
font-weight: 700;
}
.map-info {
position: absolute;
left: 12px;
@@ -587,7 +697,7 @@ label {
left: 0;
z-index: 1200;
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
grid-template-columns: repeat(5, minmax(0, 1fr));
height: var(--nav-height);
padding-bottom: env(safe-area-inset-bottom);
border-top: 1px solid #bcc7cd;
@@ -645,6 +755,16 @@ footer {
display: none;
}
@media (min-width: 701px) and (max-width: 900px) {
.map-measure-tools {
top: 126px;
}
.map-measure-tools.search-open {
top: 194px;
}
}
@media (max-width: 700px) {
.map-toolbar {
top: 8px;
@@ -688,6 +808,22 @@ footer {
top: 136px;
}
.map-measure-tools,
.map-measure-tools.search-open {
top: 126px;
right: 8px;
left: 8px;
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.map-measure-tools.search-open {
top: 194px;
}
.map-measure-tools > span {
display: none;
}
.gps-main,
.gps-center {
padding: 0 8px;
+786 -23
View File
@@ -7,11 +7,21 @@ const lmeState = {
cadastreLayers: ["CP.CadastralParcel", "codice_plla", "CP.CadastralZoning", "fabbricati"],
cadastreOpacity: 0.75,
imported: null,
importedMeasurements: null,
drawings: null,
drawingMeasurements: null,
drawControl: null,
activeDrawHandler: null,
drawEventsBound: false,
includeKmlSheetLayer: false,
showImportedMeasurements: false,
showDrawingMeasurements: true,
measurementRefreshTimer: null,
gpsMarker: null,
gpsAccuracy: null,
gpsPositionVisible: true,
hasLiveGpsFix: false,
lastAccuracy: 0,
gpsTrail: null,
selectedParcelsLayer: null,
gpsParcelLayer: null,
@@ -33,6 +43,7 @@ const cadastreCrs = L.extend({}, L.CRS.EPSG4326, { code: "EPSG:4258" });
window.lmeMap = {
init,
showSearchResult,
showInitialPosition,
displayOfficialParcel,
exportCadastreView,
closeCadastrePreview,
@@ -40,7 +51,11 @@ window.lmeMap = {
clearMapElements,
fitImported,
clearImported,
setIncludeKmlSheetLayer,
setImportedMeasurementsVisible,
setDrawingMeasurementsVisible,
addProjectMarker,
startMeasurementDrawing,
setDrawToolsVisible,
clearDrawings,
createProjectSnapshot,
@@ -58,6 +73,7 @@ window.lmeMap = {
centerOnGps,
toggleTrail,
setNativeGpsPosition,
setGpsPositionVisible,
setGpsError,
resize,
showInfo: setInfo
@@ -114,6 +130,8 @@ function init() {
lmeState.currentBase = lmeState.baseLayers.satellite.addTo(lmeState.map);
lmeState.imported = L.featureGroup().addTo(lmeState.map);
lmeState.drawings = L.featureGroup().addTo(lmeState.map);
lmeState.importedMeasurements = L.layerGroup().addTo(lmeState.map);
lmeState.drawingMeasurements = L.layerGroup().addTo(lmeState.map);
lmeState.selectedParcelsLayer = L.featureGroup().addTo(lmeState.map);
lmeState.gpsParcelLayer = L.featureGroup().addTo(lmeState.map);
lmeState.gpsTrail = L.polyline([], { color: "#f97316", weight: 4, opacity: 0.85 }).addTo(lmeState.map);
@@ -133,7 +151,10 @@ function init() {
L.popup().setLatLng(event.latlng).setContent(info).openOn(lmeState.map);
}
});
lmeState.map.on("moveend", () => void updateAzureAttribution());
lmeState.map.on("moveend", () => {
void updateAzureAttribution();
scheduleMeasurementRefresh();
});
document.getElementById("closeWmsPreview")?.addEventListener("click", closeCadastrePreview);
document.getElementById("wmsPreview")?.addEventListener("click", event => {
@@ -162,6 +183,23 @@ 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);
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();
}
function displayOfficialParcel(xmlText, latitude, longitude, parcel, label, shouldFit) {
const lat = Number(latitude);
const lon = Number(longitude);
@@ -417,7 +455,8 @@ function bindFileImport() {
}
try {
const geojson = await readGisFile(file);
const result = await readGisFile(file);
const geojson = result.geojson;
const layer = 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 }),
@@ -427,10 +466,18 @@ function bindFileImport() {
}
}).addTo(lmeState.imported);
fitLayer(layer);
setInfo(`Caricato ${file.name}`);
refreshImportedMeasurements();
const featureCount = geojson.features.length;
const ignored = result.ignoredCount
? `; esclusi ${result.ignoredCount} elementi del foglio o non particella`
: "";
const reprojected = result.reprojected ? "; coordinate Web Mercator convertite" : "";
setInfo(`Caricato ${file.name}: ${featureCount} elementi${ignored}${reprojected}.`);
updateGpsInsideState();
} catch (error) {
setInfo(`File non leggibile: ${error.message}`);
} finally {
event.target.value = "";
}
});
lmeState.fileImportBound = true;
@@ -440,28 +487,370 @@ async function readGisFile(file) {
const lowerName = file.name.toLowerCase();
if (lowerName.endsWith(".geojson") || lowerName.endsWith(".json")) {
return JSON.parse(await file.text());
const text = (await readFileText(file)).replace(/^\uFEFF/, "").trim();
if (!text) {
throw new Error("GeoJSON vuoto");
}
let parsed;
try {
parsed = JSON.parse(text);
if (typeof parsed === "string") {
parsed = JSON.parse(parsed);
}
} catch (error) {
throw new Error(`GeoJSON non valido: ${error.message}`);
}
return normalizeGeoJson(parsed, file.name);
}
if (lowerName.endsWith(".kml")) {
return kmlTextToGeoJson(await file.text());
return normalizeKmlFiles([{ name: file.name, text: await readFileText(file) }]);
}
if (lowerName.endsWith(".kmz")) {
const zip = await JSZip.loadAsync(await file.arrayBuffer());
const kmlName = Object.keys(zip.files).find(name => name.toLowerCase().endsWith(".kml"));
if (!kmlName) {
const kmlEntries = Object.values(zip.files).filter(entry =>
!entry.dir
&& !entry.name.startsWith("__MACOSX/")
&& entry.name.toLowerCase().endsWith(".kml"));
if (!kmlEntries.length) {
throw new Error("KMZ senza file KML interno");
}
return kmlTextToGeoJson(await zip.files[kmlName].async("text"));
const files = await Promise.all(kmlEntries.map(async entry => ({
name: entry.name,
text: await entry.async("text")
})));
return normalizeKmlFiles(files);
}
throw new Error("Formato supportato: KML, KMZ, GeoJSON");
}
function kmlTextToGeoJson(text) {
function readFileText(file) {
if (typeof file.text === "function") {
return file.text();
}
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result || ""));
reader.onerror = () => reject(new Error("lettura del file non riuscita"));
reader.readAsText(file);
});
}
function normalizeGeoJson(value, fileName) {
let root;
if (Array.isArray(value)) {
root = {
type: "FeatureCollection",
features: value.map(item => item?.type === "Feature"
? item
: { type: "Feature", properties: {}, geometry: item })
};
} else if (value?.type === "FeatureCollection") {
root = value;
} else if (value?.type === "Feature") {
root = { type: "FeatureCollection", features: [value], crs: value.crs };
} else if (isGeoJsonGeometry(value)) {
root = {
type: "FeatureCollection",
features: [{ type: "Feature", properties: {}, geometry: value }],
crs: value.crs
};
} else {
throw new Error("il contenuto non e' un Feature, una geometria o una FeatureCollection");
}
root.features = (root.features || []).filter(feature => feature?.type === "Feature" && feature.geometry);
if (!root.features.length) {
throw new Error("nessuna geometria presente nel GeoJSON");
}
root.features.forEach(feature => {
feature.properties = feature.properties && typeof feature.properties === "object"
? feature.properties
: {};
feature.properties._lmeSource = feature.properties._lmeSource || fileName;
});
const crsText = root.crs ? JSON.stringify(root.crs).toUpperCase() : "";
const coordinates = collectGeoJsonCoordinates(root);
const hasProjectedCoordinates = coordinates.some(point => Math.abs(point[0]) > 180 || Math.abs(point[1]) > 90);
const webMercator = /EPSG[^0-9]*(3857|900913)/.test(crsText)
|| (!crsText && hasProjectedCoordinates && coordinates.every(point =>
Math.abs(point[0]) <= 20037508.35 && Math.abs(point[1]) <= 20048966.1));
if (webMercator) {
root.features.forEach(feature => {
feature.geometry = transformGeoJsonGeometry(feature.geometry, webMercatorToWgs84);
});
} else if (crsText && !/(4326|4258|CRS84|CRS:84)/.test(crsText)) {
throw new Error(`sistema di coordinate non supportato (${crsText.slice(0, 80)})`);
}
const normalizedCoordinates = collectGeoJsonCoordinates(root);
if (!normalizedCoordinates.length || normalizedCoordinates.some(point =>
!Number.isFinite(point[0])
|| !Number.isFinite(point[1])
|| Math.abs(point[0]) > 180
|| Math.abs(point[1]) > 90)) {
throw new Error("coordinate non valide o non espresse in WGS84/EPSG:4326");
}
delete root.crs;
return { geojson: root, ignoredCount: 0, reprojected: webMercator };
}
function isGeoJsonGeometry(value) {
return [
"Point",
"MultiPoint",
"LineString",
"MultiLineString",
"Polygon",
"MultiPolygon",
"GeometryCollection"
].includes(value?.type);
}
function collectGeoJsonCoordinates(geojson) {
const points = [];
const visitGeometry = geometry => {
if (!geometry) {
return;
}
if (geometry.type === "GeometryCollection") {
(geometry.geometries || []).forEach(visitGeometry);
return;
}
const visit = coordinates => {
if (Array.isArray(coordinates)
&& coordinates.length >= 2
&& typeof coordinates[0] === "number"
&& typeof coordinates[1] === "number") {
points.push(coordinates);
return;
}
if (Array.isArray(coordinates)) {
coordinates.forEach(visit);
}
};
visit(geometry.coordinates);
};
(geojson.features || []).forEach(feature => visitGeometry(feature.geometry));
return points;
}
function transformGeoJsonGeometry(geometry, transform) {
if (!geometry) {
return geometry;
}
if (geometry.type === "GeometryCollection") {
return {
...geometry,
geometries: (geometry.geometries || []).map(item => transformGeoJsonGeometry(item, transform))
};
}
const visit = coordinates => {
if (Array.isArray(coordinates)
&& coordinates.length >= 2
&& typeof coordinates[0] === "number"
&& typeof coordinates[1] === "number") {
return transform(coordinates);
}
return Array.isArray(coordinates) ? coordinates.map(visit) : coordinates;
};
return { ...geometry, coordinates: visit(geometry.coordinates) };
}
function webMercatorToWgs84(coordinate) {
const longitude = coordinate[0] * 180 / 20037508.34;
const latitudeRadians = Math.PI / 2 - 2 * Math.atan(Math.exp(-coordinate[1] / 6378137));
return [longitude, latitudeRadians * 180 / Math.PI, ...coordinate.slice(2)];
}
function normalizeKmlFiles(files) {
const features = files.flatMap(file => kmlTextToGeoJson(file.text, file.name));
if (!features.length) {
throw new Error("KML senza geometrie utilizzabili");
}
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");
}
return {
geojson: { type: "FeatureCollection", features: selected },
ignoredCount: lmeState.includeKmlSheetLayer ? 0 : Math.max(0, polygonParts.length - selected.length),
reprojected: false
};
}
function kmlTextToGeoJson(text, sourceName) {
const xml = new DOMParser().parseFromString(text, "text/xml");
return toGeoJSON.kml(xml);
if (xml.getElementsByTagName("parsererror").length) {
throw new Error(`KML non valido (${sourceName})`);
}
const tree = toGeoJSON.kmlWithFolders(xml, { skipNullGeometry: true });
const features = [];
const visit = (node, folders) => {
if (node?.type === "Feature") {
node.properties = {
...(node.properties || {}),
_lmeFolder: folders.filter(Boolean).join(" / "),
_lmeSource: sourceName
};
features.push(node);
return;
}
const nextFolders = node?.type === "folder"
? [...folders, node.meta?.name || ""]
: folders;
(node?.children || []).forEach(child => visit(child, nextFolders));
};
visit(tree, []);
return features;
}
function filterKmlParcelFeatures(features) {
const filtered = features.filter(feature => {
const properties = feature.properties || {};
if (properties["@geometry-type"] === "groundoverlay") {
return false;
}
const name = String(properties.name || properties.Name || properties.LABEL || "").trim();
const identity = [name, properties.layer, properties.Layer, properties.type, properties.Tipo]
.filter(Boolean)
.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;
});
return removeLikelySheetOutlines(filtered);
}
function splitKmlPolygonFeatures(features) {
const result = [];
const addGeometry = (feature, geometry, partIndex) => {
if (!geometry) {
return;
}
if (geometry.type === "Polygon") {
result.push({
...feature,
properties: { ...(feature.properties || {}), _lmePart: partIndex },
geometry
});
return;
}
if (geometry.type === "MultiPolygon") {
(geometry.coordinates || []).forEach((coordinates, index) => addGeometry(
feature,
{ type: "Polygon", coordinates },
`${partIndex}.${index}`));
return;
}
if (geometry.type === "GeometryCollection") {
(geometry.geometries || []).forEach((item, index) => addGeometry(feature, item, `${partIndex}.${index}`));
}
};
features.forEach((feature, index) => addGeometry(feature, feature.geometry, index));
return result;
}
function removeLikelySheetOutlines(features) {
let remaining = [...features];
while (remaining.length >= 2) {
const candidates = remaining
.map(feature => ({ feature, bounds: geoJsonBounds(feature.geometry) }))
.filter(item => item.bounds);
if (candidates.length < 2) {
break;
}
const largest = candidates.reduce((current, item) =>
boundsArea(item.bounds) > boundsArea(current.bounds) ? item : current);
if (isStrongParcelFeature(largest.feature)) {
break;
}
const others = candidates.filter(item => item !== largest);
const comparisonAreas = others.map(item => boundsArea(item.bounds)).sort((a, b) => a - b);
const referenceArea = comparisonAreas[Math.floor(comparisonAreas.length / 2)];
const contained = others.filter(item => boundsContains(largest.bounds, boundsCenter(item.bounds))).length;
const minimumContained = candidates.length === 2 ? 1 : Math.ceil(others.length * 0.6);
const areaFactor = 2.5;
const looksLikeSheet = referenceArea > 0
&& boundsArea(largest.bounds) > referenceArea * areaFactor
&& contained >= minimumContained;
if (!looksLikeSheet) {
break;
}
remaining = remaining.filter(feature => feature !== largest.feature);
}
return remaining;
}
function isStrongParcelFeature(feature) {
const properties = feature?.properties || {};
const name = String(properties.name || properties.Name || properties.LABEL || "").trim();
const context = [name, properties.layer, properties.Layer, properties.type, properties.Tipo, properties._lmeFolder]
.filter(Boolean)
.join(" ");
return /particell|mappal|parcel/i.test(context)
|| /^[a-z]?\s*\d+[a-z]?(?:[\/. -]\d+[a-z]?)?$/i.test(name);
}
function geoJsonBounds(geometry) {
const wrapper = { features: [{ geometry }] };
const points = collectGeoJsonCoordinates(wrapper);
if (!points.length) {
return null;
}
return points.reduce((bounds, point) => ({
west: Math.min(bounds.west, point[0]),
south: Math.min(bounds.south, point[1]),
east: Math.max(bounds.east, point[0]),
north: Math.max(bounds.north, point[1])
}), { west: Infinity, south: Infinity, east: -Infinity, north: -Infinity });
}
function boundsArea(bounds) {
return Math.max(0, bounds.east - bounds.west) * Math.max(0, bounds.north - bounds.south);
}
function boundsCenter(bounds) {
return [(bounds.west + bounds.east) / 2, (bounds.south + bounds.north) / 2];
}
function boundsContains(bounds, point) {
return point[0] >= bounds.west && point[0] <= bounds.east
&& point[1] >= bounds.south && point[1] <= bounds.north;
}
function setIncludeKmlSheetLayer(enabled) {
lmeState.includeKmlSheetLayer = Boolean(enabled);
setInfo(lmeState.includeKmlSheetLayer
? "Importazione KML/KMZ: verranno inclusi anche foglio e altri elementi."
: "Importazione KML/KMZ: verranno caricate solo le particelle riconosciute.");
}
function setImportedMeasurementsVisible(enabled) {
lmeState.showImportedMeasurements = Boolean(enabled);
refreshImportedMeasurements();
setInfo(lmeState.showImportedMeasurements
? "Misure dei file GIS visibili."
: "Misure dei file GIS nascoste.");
}
function setDrawingMeasurementsVisible(enabled) {
lmeState.showDrawingMeasurements = Boolean(enabled);
refreshDrawingMeasurements();
setInfo(lmeState.showDrawingMeasurements
? "Misure dei disegni visibili."
: "Misure dei disegni nascoste.");
}
function fitImported() {
@@ -470,6 +859,7 @@ function fitImported() {
function clearImported() {
lmeState.imported.clearLayers();
lmeState.importedMeasurements.clearLayers();
setInfo("File GIS rimossi.");
updateGpsInsideState();
}
@@ -483,6 +873,7 @@ function addProjectMarker(name) {
properties: { name: label }
};
marker.bindPopup(`<strong>${escapeHtml(label)}</strong><br>${center.lat.toFixed(6)}, ${center.lng.toFixed(6)}`).openPopup();
refreshDrawingMeasurements();
setInfo(`POI aggiunto: ${label}`);
}
@@ -496,25 +887,107 @@ function enableDrawTools() {
position: "topright",
edit: { featureGroup: lmeState.drawings },
draw: {
circle: false,
circle: { metric: true, feet: false },
circlemarker: false,
marker: true,
polygon: true,
polyline: true,
polygon: { metric: true, feet: false, showArea: true, allowIntersection: false },
polyline: { metric: true, feet: false, showLength: true },
rectangle: true
}
});
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.");
}
function startMeasurementDrawing(mode) {
if (!lmeState.map) {
return;
}
if (!lmeState.drawEventsBound) {
enableDrawTools();
setDrawToolsVisible(false);
}
if (lmeState.activeDrawHandler) {
lmeState.activeDrawHandler.disable();
}
const handlers = {
area: () => new L.Draw.Polygon(lmeState.map, {
allowIntersection: false,
showArea: true,
metric: true,
feet: false,
shapeOptions: { color: "#f97316", weight: 4, fillColor: "#fb923c", fillOpacity: 0.2 }
}),
distance: () => new L.Draw.Polyline(lmeState.map, {
metric: true,
feet: false,
showLength: true,
shapeOptions: { color: "#f97316", weight: 4, opacity: 0.95 }
}),
circle: () => new L.Draw.Circle(lmeState.map, {
metric: true,
feet: false,
showRadius: true,
shapeOptions: { color: "#f97316", weight: 4, fillColor: "#fb923c", fillOpacity: 0.2 }
})
};
const createHandler = handlers[mode];
if (!createHandler) {
setInfo("Modalita di misura non riconosciuta.");
return;
}
lmeState.activeDrawHandler = createHandler();
lmeState.activeDrawHandler.enable();
const labels = {
area: "Tocca i vertici dell'area; chiudi toccando il primo punto.",
distance: "Tocca i punti del percorso; termina sull'ultimo punto.",
circle: "Tocca il centro e trascina fino al raggio desiderato."
};
setInfo(labels[mode]);
}
function annotateDrawingLayer(layer, layerType) {
layer.feature = layer.feature || { type: "Feature", properties: {} };
layer.feature.properties = layer.feature.properties || {};
if (layer instanceof L.Circle) {
layer.feature.properties._lmeShape = "circle";
layer.feature.properties._lmeRadius = layer.getRadius();
} else if (layerType) {
layer.feature.properties._lmeShape = layerType;
}
}
function setDrawToolsVisible(visible) {
if (visible) {
enableDrawTools();
@@ -547,10 +1020,238 @@ function clearDrawings() {
}
lmeState.drawings.clearLayers();
lmeState.drawingMeasurements.clearLayers();
updateGpsInsideState();
setInfo("Disegni e POI eliminati dalla mappa.");
}
function scheduleMeasurementRefresh() {
window.clearTimeout(lmeState.measurementRefreshTimer);
lmeState.measurementRefreshTimer = window.setTimeout(() => {
refreshImportedMeasurements();
refreshDrawingMeasurements();
}, 80);
}
function refreshImportedMeasurements() {
renderMeasurements(
lmeState.imported,
lmeState.importedMeasurements,
lmeState.showImportedMeasurements,
"imported");
}
function refreshDrawingMeasurements() {
renderMeasurements(
lmeState.drawings,
lmeState.drawingMeasurements,
lmeState.showDrawingMeasurements,
"drawing");
}
function renderMeasurements(sourceGroup, targetGroup, visible, sourceType) {
if (!sourceGroup || !targetGroup) {
return;
}
targetGroup.clearLayers();
if (!visible) {
return;
}
const context = {
count: 0,
max: 600,
showSides: lmeState.map.getZoom() >= 17,
bounds: lmeState.map.getBounds(),
sourceType
};
visitMeasurableLayers(sourceGroup, layer => {
if (context.count >= context.max || !layerIsInView(layer, context.bounds)) {
return;
}
if (layer instanceof L.Circle) {
renderCircleMeasurement(layer, targetGroup, context);
} else if (layer instanceof L.Polygon) {
renderPolygonMeasurement(layer, targetGroup, context);
} else if (layer instanceof L.Polyline) {
renderPolylineMeasurement(layer, targetGroup, context);
}
});
}
function visitMeasurableLayers(layer, visitor) {
if (layer instanceof L.Circle || layer instanceof L.Polygon || layer instanceof L.Polyline) {
visitor(layer);
return;
}
if (typeof layer.eachLayer === "function") {
layer.eachLayer(child => visitMeasurableLayers(child, visitor));
}
}
function layerIsInView(layer, mapBounds) {
if (typeof layer.getBounds === "function") {
const bounds = layer.getBounds();
return !bounds.isValid || !bounds.isValid() || bounds.intersects(mapBounds);
}
if (typeof layer.getLatLng === "function") {
return mapBounds.contains(layer.getLatLng());
}
return true;
}
function renderCircleMeasurement(layer, targetGroup, context) {
const radius = layer.getRadius();
const area = Math.PI * radius * radius;
const circumference = 2 * Math.PI * radius;
addMeasurementLabel(
targetGroup,
layer.getLatLng(),
`S: ${formatArea(area)}<br>R: ${formatDistance(radius)} · C: ${formatDistance(circumference)}`,
"summary",
context);
}
function renderPolygonMeasurement(layer, targetGroup, context) {
const polygons = polygonLatLngGroups(layer.getLatLngs());
let area = 0;
let perimeter = 0;
polygons.forEach(rings => {
rings.forEach((ring, index) => {
const ringArea = Math.abs(L.GeometryUtil.geodesicArea(ring));
area += index === 0 ? ringArea : -ringArea;
perimeter += latLngPathLength(ring, true);
if (context.showSides) {
addSegmentLabels(ring, true, targetGroup, context);
}
});
});
const center = typeof layer.getCenter === "function"
? layer.getCenter()
: layer.getBounds().getCenter();
addMeasurementLabel(
targetGroup,
center,
`S: ${formatArea(Math.max(0, area))}<br>P: ${formatDistance(perimeter)}`,
"summary",
context);
}
function renderPolylineMeasurement(layer, targetGroup, context) {
const lines = lineLatLngGroups(layer.getLatLngs());
const length = lines.reduce((total, line) => total + latLngPathLength(line, false), 0);
if (context.showSides) {
lines.forEach(line => addSegmentLabels(line, false, targetGroup, context));
}
const longest = lines.reduce((current, line) => line.length > current.length ? line : current, []);
if (longest.length) {
addMeasurementLabel(
targetGroup,
longest[Math.floor(longest.length / 2)],
`L: ${formatDistance(length)}`,
"summary",
context);
}
}
function polygonLatLngGroups(latLngs) {
if (!Array.isArray(latLngs) || !latLngs.length) {
return [];
}
if (isLatLng(latLngs[0])) {
return [[latLngs]];
}
if (Array.isArray(latLngs[0]) && isLatLng(latLngs[0][0])) {
return [latLngs];
}
return latLngs.flatMap(polygonLatLngGroups);
}
function lineLatLngGroups(latLngs) {
if (!Array.isArray(latLngs) || !latLngs.length) {
return [];
}
if (isLatLng(latLngs[0])) {
return [latLngs];
}
return latLngs.flatMap(lineLatLngGroups);
}
function isLatLng(value) {
return value && Number.isFinite(value.lat) && Number.isFinite(value.lng);
}
function latLngPathLength(points, closed) {
if (points.length < 2) {
return 0;
}
let total = 0;
for (let index = 1; index < points.length; index += 1) {
total += lmeState.map.distance(points[index - 1], points[index]);
}
if (closed && !points[0].equals(points[points.length - 1])) {
total += lmeState.map.distance(points[points.length - 1], points[0]);
}
return total;
}
function addSegmentLabels(points, closed, targetGroup, context) {
if (points.length < 2) {
return;
}
const segmentCount = closed ? points.length : points.length - 1;
for (let index = 0; index < segmentCount && context.count < context.max; index += 1) {
const start = points[index];
const end = points[(index + 1) % points.length];
if (start.equals(end)) {
continue;
}
addMeasurementLabel(
targetGroup,
L.latLng((start.lat + end.lat) / 2, (start.lng + end.lng) / 2),
formatDistance(lmeState.map.distance(start, end)),
"side",
context);
}
}
function addMeasurementLabel(targetGroup, latLng, html, labelType, context) {
if (context.count >= context.max) {
return;
}
L.marker(latLng, {
interactive: false,
keyboard: false,
icon: L.divIcon({
className: `lme-measure-label ${context.sourceType} ${labelType}`,
html: `<span>${html}</span>`,
iconSize: null
})
}).addTo(targetGroup);
context.count += 1;
}
function formatDistance(meters) {
if (meters >= 1000) {
return `${formatNumber(meters / 1000, 3)} km`;
}
return `${formatNumber(meters, meters < 100 ? 1 : 0)} m`;
}
function formatArea(squareMeters) {
if (squareMeters >= 10000) {
return `${formatNumber(squareMeters / 10000, 4)} ha`;
}
return `${formatNumber(squareMeters, squareMeters < 100 ? 1 : 0)} m²`;
}
function formatNumber(value, digits) {
return new Intl.NumberFormat("it-IT", {
minimumFractionDigits: 0,
maximumFractionDigits: digits
}).format(value);
}
function createProjectSnapshot(includeCadastralParcels) {
const center = lmeState.map.getCenter();
return JSON.stringify({
@@ -589,13 +1290,29 @@ function loadProjectSnapshot(raw, projectName) {
lmeState.drawings.clearLayers();
lmeState.imported.clearLayers();
lmeState.drawingMeasurements.clearLayers();
lmeState.importedMeasurements.clearLayers();
lmeState.selectedParcelsLayer.clearLayers();
lmeState.gpsParcelLayer.clearLayers();
L.geoJSON(data.drawings || emptyFeatureCollection(), {
const restoredDrawings = L.geoJSON(data.drawings || emptyFeatureCollection(), {
style: { color: "#f97316", weight: 3, fillOpacity: 0.16 },
pointToLayer: (feature, latlng) => {
const properties = feature?.properties || {};
if (properties._lmeShape === "circle" && Number(properties._lmeRadius) > 0) {
return L.circle(latlng, {
radius: Number(properties._lmeRadius),
color: "#f97316",
weight: 3,
fillColor: "#fb923c",
fillOpacity: 0.2
});
}
return L.marker(latlng, { draggable: true });
},
onEachFeature: bindStoredFeaturePopup
}).addTo(lmeState.drawings);
});
restoredDrawings.eachLayer(layer => lmeState.drawings.addLayer(layer));
L.geoJSON(data.imported || emptyFeatureCollection(), {
style: { color: "#22c55e", weight: 3, opacity: 0.95, fillOpacity: 0.18 },
pointToLayer: (feature, latlng) => L.circleMarker(latlng, {
@@ -621,6 +1338,8 @@ function loadProjectSnapshot(raw, projectName) {
lmeState.gpsTrailPoints = Array.isArray(data.trail) ? data.trail : [];
lmeState.gpsTrail.setLatLngs(lmeState.gpsTrailPoints);
refreshImportedMeasurements();
refreshDrawingMeasurements();
const projectLayers = L.featureGroup([
lmeState.drawings,
@@ -956,6 +1675,8 @@ function clearMapElements() {
lmeState.gpsParcelLayer.clearLayers();
lmeState.imported.clearLayers();
lmeState.drawings.clearLayers();
lmeState.importedMeasurements.clearLayers();
lmeState.drawingMeasurements.clearLayers();
lmeState.gpsTrailPoints = [];
lmeState.gpsTrail.setLatLngs([]);
updateGpsInsideState();
@@ -1006,6 +1727,25 @@ function setNativeGpsPosition(location) {
});
}
function setGpsPositionVisible(enabled) {
lmeState.gpsPositionVisible = Boolean(enabled);
if (!lmeState.gpsPositionVisible) {
if (lmeState.gpsMarker && lmeState.map.hasLayer(lmeState.gpsMarker)) {
lmeState.map.removeLayer(lmeState.gpsMarker);
}
if (lmeState.gpsAccuracy && lmeState.map.hasLayer(lmeState.gpsAccuracy)) {
lmeState.map.removeLayer(lmeState.gpsAccuracy);
}
setInfo("Punto e cerchio GPS nascosti. Il rilevamento continua.");
return;
}
if (lmeState.hasLiveGpsFix && lmeState.lastPosition) {
updateGpsPositionLayers(lmeState.lastPosition, lmeState.lastAccuracy);
}
setInfo("Punto e cerchio GPS visibili.");
}
function setGpsError(error) {
setText("gpsState", "GPS non disponibile");
setInfo(error || "Errore GPS.");
@@ -1030,14 +1770,12 @@ function onGpsPosition(position) {
const { latitude, longitude, accuracy } = position.coords;
const latlng = [latitude, longitude];
lmeState.lastPosition = latlng;
if (!lmeState.gpsMarker) {
lmeState.gpsMarker = L.marker(latlng, { title: "La tua posizione" }).addTo(lmeState.map);
lmeState.gpsAccuracy = L.circle(latlng, { radius: accuracy, color: "#2563eb", weight: 2, fillColor: "#60a5fa", fillOpacity: 0.16 }).addTo(lmeState.map);
lmeState.lastAccuracy = Math.max(0, Number(accuracy) || 0);
const firstLiveFix = !lmeState.hasLiveGpsFix;
lmeState.hasLiveGpsFix = true;
updateGpsPositionLayers(latlng, lmeState.lastAccuracy);
if (firstLiveFix) {
lmeState.map.setView(latlng, 19);
} else {
lmeState.gpsMarker.setLatLng(latlng);
lmeState.gpsAccuracy.setLatLng(latlng).setRadius(accuracy);
}
if (lmeState.gpsTrailEnabled) {
@@ -1045,10 +1783,35 @@ function onGpsPosition(position) {
lmeState.gpsTrail.setLatLngs(lmeState.gpsTrailPoints);
}
setText("gpsState", `${latitude.toFixed(6)}, ${longitude.toFixed(6)} - precisione ${Math.round(accuracy)} m`);
setText("gpsState", `${latitude.toFixed(6)}, ${longitude.toFixed(6)} - precisione ${Math.round(lmeState.lastAccuracy)} m`);
updateGpsInsideState();
}
function updateGpsPositionLayers(latlng, accuracy) {
if (!lmeState.gpsPositionVisible) {
return;
}
if (!lmeState.gpsMarker) {
lmeState.gpsMarker = L.marker(latlng, { title: "La tua posizione" });
lmeState.gpsAccuracy = L.circle(latlng, {
radius: accuracy,
color: "#2563eb",
weight: 2,
fillColor: "#60a5fa",
fillOpacity: 0.16
});
} else {
lmeState.gpsMarker.setLatLng(latlng);
lmeState.gpsAccuracy.setLatLng(latlng).setRadius(accuracy);
}
if (!lmeState.map.hasLayer(lmeState.gpsMarker)) {
lmeState.gpsMarker.addTo(lmeState.map);
}
if (!lmeState.map.hasLayer(lmeState.gpsAccuracy)) {
lmeState.gpsAccuracy.addTo(lmeState.map);
}
}
function onGpsError(error) {
setText("gpsState", "GPS non autorizzato o non disponibile");
setInfo(error.message || "Errore GPS.");