Compare commits

...
8 Commits
10 changed files with 1386 additions and 181 deletions

No files matched your search

+362 -57
View File
@@ -4,14 +4,16 @@
@inject CadastralCatalogService CatalogService
@inject OfficialCadastreService OfficialCadastreService
@inject LocationSearchService LocationSearchService
@inject NetworkLocationService NetworkLocationService
@inject AzureMapsService AzureMapsService
@inject ProjectStorageService ProjectStorageService
@inject MapExportService MapExportService
@implements IAsyncDisposable
<PageTitle>LME Mappe Catastali</PageTitle>
<div class="map-app">
<section class="map-stage">
<section class="map-stage @(ActiveTab == "search" ? "search-active" : null)">
<div id="map"></div>
<header class="map-toolbar">
@@ -149,28 +151,117 @@
</div>
</section>
}
else if (ActiveTab == "projects")
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="@ImportParcelsOnly" @onchange="ToggleImportParcelsOnly" />
<span>KML/KMZ: importa solo le particelle</span>
<input type="checkbox" @bind="IncludeKmlSheetLayer" @bind:after="ApplyKmlSheetLayerOption" />
<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" @bind="ShowImportedSheetLayer" @bind:after="ApplyImportedSheetLayerVisibility" />
<span>Mostra cornice/layer del foglio importato</span>
</label>
<small class="field-help">La cornice grande resta separata dalle particelle e puo essere nascosta anche nei progetti salvati.</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</button>
<button class="secondary-command" @onclick="ClearImportedLayers">Pulisci</button>
<button @onclick="FitImportedLayers">Inquadra dati</button>
<button class="secondary-command" @onclick="ClearImportedLayers">Rimuovi dati</button>
</div>
</section>
<h2>Archivio progetti</h2>
<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 strumenti sulla mappa" : "Mostra strumenti sulla mappa")
</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 == "save")
{
<section class="panel-content">
<section class="panel-section">
<h2>Esporta contenuto mappa</h2>
<label>
Nome file
<input @bind="ExportFileName" @bind:event="oninput" placeholder="Es. Rilievo San Nicola" maxlength="80" />
</label>
<label>
Formato
<select @bind="ExportFormat">
<option value="geojson">GeoJSON</option>
<option value="kml">KML</option>
<option value="kmz">KMZ compresso</option>
</select>
</label>
<div class="export-options" role="group" aria-label="Oggetti da esportare">
<label class="toggle-line project-save-option">
<input type="checkbox" @bind="ExportImported" />
<span>Particelle e dati GIS importati</span>
</label>
<label class="toggle-line project-save-option">
<input type="checkbox" @bind="ExportImportedSheets" />
<span>Cornici, fogli e riquadri KMZ</span>
</label>
<label class="toggle-line project-save-option">
<input type="checkbox" @bind="ExportCadastral" />
<span>Particelle catastali rosse e GPS</span>
</label>
<label class="toggle-line project-save-option">
<input type="checkbox" @bind="ExportDrawings" />
<span>Disegni, aree, linee e cerchi</span>
</label>
<label class="toggle-line project-save-option">
<input type="checkbox" @bind="ExportPoi" />
<span>Punti di interesse</span>
</label>
<label class="toggle-line project-save-option">
<input type="checkbox" @bind="ExportTrail" />
<span>Traccia GPS registrata</span>
</label>
</div>
<button class="primary-command" @onclick="ExportMapFile" disabled="@(ExportBusy || string.IsNullOrWhiteSpace(ExportFileName))">
@(ExportBusy ? "Preparazione file..." : "Esporta e salva file")
</button>
<small class="field-help">KML e KMZ sono compatibili con Google Earth. Gli sfondi satellitari e il WMS non vengono incorporati nel file vettoriale.</small>
</section>
</section>
}
else if (ActiveTab == "projects")
{
<section class="panel-content">
<section class="panel-section">
<h2>Salva progetto</h2>
<label>
Nome progetto
<input @bind="NewProjectName" @bind:event="oninput" placeholder="Es. Rilievo San Nicola" maxlength="80" />
@@ -180,7 +271,10 @@
<span>Includi le particelle catastali rosse</span>
</label>
<button class="primary-command" @onclick="SaveProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(NewProjectName))">Salva progetto</button>
</section>
<section class="panel-section">
<h2>Apri progetto</h2>
<label>
Progetto salvato
<select value="@SelectedProjectId" @onchange="SelectProject" disabled="@(Projects.Count == 0 || ProjectBusy)">
@@ -192,38 +286,35 @@
</select>
</label>
<div class="button-row">
<button @onclick="LoadProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Carica</button>
<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>
<h2>Misura e disegna</h2>
<div class="measurement-mode-grid" aria-label="Strumenti di misura">
<button @onclick='() => StartMeasurementDrawing("area")'>Area</button>
<button @onclick='() => StartMeasurementDrawing("distance")'>Distanza</button>
<button @onclick='() => StartMeasurementDrawing("circle")'>Cerchio</button>
</div>
<section class="panel-section">
<h2>Visualizzazione progetto</h2>
<label class="toggle-line project-save-option">
<input type="checkbox" @bind="ShowImportedSheetLayer" @bind:after="ApplyImportedSheetLayerVisibility" />
<span>Mostra cornice/layer del foglio importato</span>
</label>
<small class="field-help">Il comando agisce subito sulla mappa e sui dati del progetto caricato.</small>
<label class="toggle-line project-save-option">
<input type="checkbox" checked="@ShowImportedMeasurements" @onchange="ToggleImportedMeasurements" />
<span>Mostra misure dei file caricati</span>
</label>
<label class="toggle-line project-save-option">
<input type="checkbox" checked="@ShowDrawingMeasurements" @onchange="ToggleDrawingMeasurements" />
<span>Mostra superficie, perimetro e lati</span>
<span>Mostra misure dei disegni</span>
</label>
<button class="secondary-command" aria-pressed="@DrawToolsVisible" @onclick="ToggleDrawTools">
@(DrawToolsVisible ? "Nascondi strumenti completi" : "Mostra strumenti completi")
</button>
<h2>POI</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="danger-command" @onclick="ClearDrawings">Elimina disegni e POI</button>
</section>
</section>
}
else if (ActiveTab == "settings")
{
<section class="panel-content">
<h2>Visualizzazione</h2>
<section class="panel-section">
<h2>Mappa e sfondo</h2>
<label>
Sfondo
<select value="@SelectedBaseLayer" @onchange="ChangeBaseLayer">
@@ -239,6 +330,14 @@
<option value="google-roadmap">Strade - Google Maps</option>
</select>
</label>
<label>
Trasparenza catasto
<input type="range" min="0" max="1" step="0.05" value="@CadastralOpacity.ToString(System.Globalization.CultureInfo.InvariantCulture)" @onchange="ChangeCadastreOpacity" />
</label>
</section>
<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" />
@@ -253,16 +352,21 @@
<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>
<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>
@@ -270,10 +374,10 @@
<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>
}
@@ -302,7 +406,9 @@
<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 == "save" ? "active" : null)" @onclick='() => SelectTab("save")'>Salvataggio</button>
<button class="@(ActiveTab == "settings" ? "active" : null)" @onclick='() => SelectTab("settings")'>Impostazioni</button>
</nav>
</section>
@@ -312,6 +418,8 @@
private string ActiveTab { get; set; } = "map";
private string SearchText { get; set; } = string.Empty;
private string NewProjectName { get; set; } = string.Empty;
private string ExportFileName { get; set; } = "Mappa";
private string ExportFormat { get; set; } = "geojson";
private string PoiName { get; set; } = string.Empty;
private string SelectedProjectId { get; set; } = string.Empty;
private string ProjectArchiveMessage { get; set; } = "Nessun progetto salvato.";
@@ -325,16 +433,26 @@
private string SelectedParcelNumber { get; set; } = string.Empty;
private string CatalogMessage { get; set; } = string.Empty;
private double? CatalogFraction { get; set; }
private double CadastralOpacity { get; set; } = 0.75;
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 ImportParcelsOnly { get; set; } = true;
private bool IncludeKmlSheetLayer { get; set; }
private bool ShowImportedSheetLayer { get; set; }
private bool ShowImportedMeasurements { get; set; }
private bool ShowDrawingMeasurements { get; set; } = true;
private bool ProjectBusy { get; set; }
private bool ExportBusy { get; set; }
private bool ExportImported { get; set; } = true;
private bool ExportImportedSheets { get; set; } = true;
private bool ExportCadastral { get; set; } = true;
private bool ExportDrawings { get; set; } = true;
private bool ExportPoi { get; set; } = true;
private bool ExportTrail { get; set; } = true;
private CancellationTokenSource? CatalogCancellation { get; set; }
private CancellationTokenSource? GpsLookupCancellation { get; set; }
private long LastGpsLookupAt;
@@ -355,7 +473,9 @@
private string PanelTitle => ActiveTab switch
{
"cadastre" => "Ricerca catastale",
"projects" => "Progetti e dati",
"data" => "Dati e disegni",
"projects" => "Archivio progetti",
"save" => "Salvataggio ed esportazione",
"settings" => "Impostazioni",
_ => string.Empty
};
@@ -363,7 +483,9 @@
private string PanelEyebrow => ActiveTab switch
{
"cadastre" => "Regione, Comune, Foglio, Particella",
"projects" => "KML, KMZ, GeoJSON e POI",
"data" => "File GIS, misure e POI",
"projects" => "Salva, apri e visualizza i tuoi lavori",
"save" => "Esporta file GIS",
"settings" => "Mappa, GPS e servizi ufficiali",
_ => string.Empty
};
@@ -415,10 +537,100 @@
if (firstRender)
{
await JS.InvokeVoidAsync("lmeMap.init");
await CenterOnInitialLocationAsync();
await MigrateLegacyProjectAsync();
}
}
private async Task ConfigureProjectMapProviderAsync(string snapshot)
{
string? baseLayer = null;
try
{
using var document = System.Text.Json.JsonDocument.Parse(snapshot);
if (document.RootElement.TryGetProperty("displayOptions", out var displayOptions)
&& displayOptions.TryGetProperty("baseLayer", out var baseLayerProperty))
{
baseLayer = baseLayerProperty.GetString();
}
}
catch
{
return;
}
try
{
if (baseLayer?.StartsWith("google-", StringComparison.Ordinal) == true
&& !string.IsNullOrWhiteSpace(GoogleMapsApiKey))
{
await JS.InvokeVoidAsync("lmeMap.configureGoogleMaps", GoogleMapsApiKey.Trim());
}
if (baseLayer?.StartsWith("azure-", StringComparison.Ordinal) == true
&& !string.IsNullOrWhiteSpace(AzureMapsSubscriptionKey))
{
await JS.InvokeVoidAsync("lmeMap.configureAzureMaps", AzureMapsSubscriptionKey.Trim());
}
}
catch
{
// Loading continues with the default map if the saved provider is unavailable.
}
}
private async Task CenterOnInitialLocationAsync()
{
NetworkLocationSnapshot? networkLocation = null;
try
{
using var networkTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(8));
networkLocation = await NetworkLocationService.GetApproximateLocationAsync(networkTimeout.Token);
}
catch
{
// An unavailable IP service must not prevent the GPS fallback.
}
if (networkLocation is not null)
{
await JS.InvokeVoidAsync(
"lmeMap.showInitialPosition",
networkLocation.Latitude,
networkLocation.Longitude,
true,
networkLocation.Label);
return;
}
try
{
using var gpsTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(18));
var location = await LocationService.GetCurrentLocationAsync(gpsTimeout.Token);
if (location is not null)
{
await JS.InvokeVoidAsync(
"lmeMap.showInitialPosition",
location.Latitude,
location.Longitude,
false,
string.Empty);
}
else
{
await JS.InvokeVoidAsync("lmeMap.showInfo", "Posizione iniziale non disponibile. La mappa resta utilizzabile normalmente.");
}
}
catch (OperationCanceledException)
{
await JS.InvokeVoidAsync("lmeMap.showInfo", "Posizione iniziale non disponibile. 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
@@ -642,6 +854,12 @@
}
}
private async Task ToggleGpsPosition(ChangeEventArgs args)
{
ShowGpsPosition = (bool?)args.Value == true;
await JS.InvokeVoidAsync("lmeMap.setGpsPositionVisible", ShowGpsPosition);
}
private async Task StartGps()
{
GpsActive = true;
@@ -748,13 +966,23 @@
}
private Task FitImportedLayers() => JS.InvokeVoidAsync("lmeMap.fitImported").AsTask();
private Task ClearImportedLayers() => JS.InvokeVoidAsync("lmeMap.clearImported").AsTask();
private async Task ClearImportedLayers()
{
ShowImportedSheetLayer = false;
await JS.InvokeVoidAsync("lmeMap.clearImported");
}
private Task AddProjectMarker() => JS.InvokeVoidAsync("lmeMap.addProjectMarker", PoiName).AsTask();
private async Task ToggleImportParcelsOnly(ChangeEventArgs args)
private async Task ApplyKmlSheetLayerOption()
{
ImportParcelsOnly = (bool?)args.Value == true;
await JS.InvokeVoidAsync("lmeMap.setImportParcelOnly", ImportParcelsOnly);
ShowImportedSheetLayer = IncludeKmlSheetLayer;
await JS.InvokeVoidAsync("lmeMap.setIncludeKmlSheetLayer", IncludeKmlSheetLayer);
await JS.InvokeVoidAsync("lmeMap.setImportedSheetLayerVisible", ShowImportedSheetLayer);
}
private Task ApplyImportedSheetLayerVisibility()
{
return JS.InvokeVoidAsync("lmeMap.setImportedSheetLayerVisible", ShowImportedSheetLayer).AsTask();
}
private async Task ToggleImportedMeasurements(ChangeEventArgs args)
@@ -769,17 +997,6 @@
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;
@@ -818,6 +1035,47 @@
return Task.CompletedTask;
}
private async Task ExportMapFile()
{
if (!ExportImported && !ExportImportedSheets && !ExportCadastral
&& !ExportDrawings && !ExportPoi && !ExportTrail)
{
await JS.InvokeVoidAsync("lmeMap.showInfo", "Seleziona almeno un tipo di oggetto da esportare.");
return;
}
ExportBusy = true;
try
{
var geoJson = await JS.InvokeAsync<string>("lmeMap.createMapExportGeoJson", new
{
includeImported = ExportImported,
includeImportedSheets = ExportImportedSheets,
includeCadastral = ExportCadastral,
includeDrawings = ExportDrawings,
includePoi = ExportPoi,
includeTrail = ExportTrail
});
var exported = await MapExportService.CreateAsync(ExportFileName, ExportFormat, geoJson);
await Share.Default.RequestAsync(new ShareFileRequest
{
Title = $"Salva o condividi {exported.FileName}",
File = new ShareFile(exported.Path, exported.MimeType)
});
await JS.InvokeVoidAsync(
"lmeMap.showInfo",
$"File {exported.FileName} pronto: {exported.FeatureCount} oggetti esportati.");
}
catch (Exception error)
{
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Esportazione non riuscita: {error.GetBaseException().Message}");
}
finally
{
ExportBusy = false;
}
}
private async Task SaveProject()
{
var name = NewProjectName.Trim();
@@ -876,8 +1134,11 @@
try
{
var snapshot = await ProjectStorageService.LoadAsync(project.Id);
await JS.InvokeVoidAsync("lmeMap.loadProjectSnapshot", snapshot, project.Name);
await ConfigureProjectMapProviderAsync(snapshot);
var displayOptions = await JS.InvokeAsync<ProjectDisplayOptions>("lmeMap.loadProjectSnapshot", snapshot, project.Name);
ApplyProjectDisplayOptions(displayOptions);
NewProjectName = project.Name;
ExportFileName = project.Name;
IncludeCadastralParcels = project.IncludesCadastralParcels;
ActiveTab = "map";
await Task.Delay(30);
@@ -893,6 +1154,25 @@
}
}
private void ApplyProjectDisplayOptions(ProjectDisplayOptions options)
{
SelectedBaseLayer = options.BaseLayer;
CadastralOpacity = options.CadastreOpacity;
IncludeKmlSheetLayer = options.IncludeKmlSheetLayer;
ShowImportedSheetLayer = options.ImportedSheetsVisible;
ShowImportedMeasurements = options.ShowImportedMeasurements;
ShowDrawingMeasurements = options.ShowDrawingMeasurements;
DrawToolsVisible = options.DrawToolsVisible;
ShowGpsPosition = options.GpsPositionVisible;
TrailEnabled = options.TrailEnabled;
var activeLayers = (options.CadastreLayers ?? []).ToHashSet(StringComparer.Ordinal);
foreach (var layer in CadastralLayers)
{
layer.Enabled = activeLayers.Contains(layer.Key);
}
}
private async Task DeleteProject()
{
var project = Projects.FirstOrDefault(item => item.Id == SelectedProjectId);
@@ -1014,7 +1294,18 @@
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Chiave Azure Maps non salvata: {error.GetBaseException().Message}");
}
}
private Task ChangeCadastreOpacity(ChangeEventArgs args) => JS.InvokeVoidAsync("lmeMap.setCadastreOpacity", args.Value?.ToString()).AsTask();
private async Task ChangeCadastreOpacity(ChangeEventArgs args)
{
var text = args.Value?.ToString();
if (!double.TryParse(text, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var value)
&& !double.TryParse(text, out value))
{
return;
}
CadastralOpacity = Math.Clamp(value, 0, 1);
await JS.InvokeVoidAsync("lmeMap.setCadastreOpacity", CadastralOpacity);
}
private async Task ToggleCadastreLayer(CadastralLayer layer, ChangeEventArgs args)
{
@@ -1049,6 +1340,20 @@
public string Detail { get; } = detail;
}
private sealed class ProjectDisplayOptions
{
public string BaseLayer { get; init; } = "satellite";
public double CadastreOpacity { get; init; } = 0.75;
public string[] CadastreLayers { get; init; } = [];
public bool IncludeKmlSheetLayer { get; init; }
public bool ImportedSheetsVisible { get; init; }
public bool ShowImportedMeasurements { get; init; }
public bool ShowDrawingMeasurements { get; init; } = true;
public bool DrawToolsVisible { get; init; }
public bool GpsPositionVisible { get; init; } = true;
public bool TrailEnabled { get; init; }
}
public ValueTask DisposeAsync()
{
CancelCatalogWork();
+2 -2
View File
@@ -28,8 +28,8 @@
<ApplicationId>com.companyname.lmemappecatastaliapp</ApplicationId>
<!-- Versions -->
<ApplicationDisplayVersion>0.2.8</ApplicationDisplayVersion>
<ApplicationVersion>12</ApplicationVersion>
<ApplicationDisplayVersion>0.2.16</ApplicationDisplayVersion>
<ApplicationVersion>20</ApplicationVersion>
<!-- To develop, package, and publish an app to the Microsoft Store, see: https://aka.ms/MauiTemplateUnpackaged -->
<WindowsPackageType>None</WindowsPackageType>
+2
View File
@@ -20,8 +20,10 @@ public static class MauiProgram
builder.Services.AddSingleton<CadastralCatalogService>();
builder.Services.AddSingleton<OfficialCadastreService>();
builder.Services.AddSingleton<LocationSearchService>();
builder.Services.AddSingleton<NetworkLocationService>();
builder.Services.AddSingleton<AzureMapsService>();
builder.Services.AddSingleton<ProjectStorageService>();
builder.Services.AddSingleton<MapExportService>();
#if DEBUG
builder.Services.AddBlazorWebViewDeveloperTools();
+9 -5
View File
@@ -10,25 +10,29 @@ App .NET MAUI Blazor Hybrid per Android, iOS, Mac Catalyst e Windows, pensata pe
- 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 esclusione di GroundOverlay e perimetri del foglio.
- 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 e puo essere mostrato o nascosto separatamente.
- Migrazione automatica dei vecchi progetti: i GroundOverlay `DOC_...` salvati in precedenza insieme alle particelle vengono riconosciuti, separati e nascosti in tempo reale dal relativo check.
- Inquadramento e pulizia dei layer importati.
- Disegno di marker, linee, poligoni e rettangoli.
- Modalita rapide Area, Distanza e Cerchio con superficie, perimetro, raggio, circonferenza e lunghezza dei singoli lati.
- Area, Distanza e Cerchio disponibili nella barra Leaflet laterale, nascosta all'avvio e controllata dal pulsante nel tab Dati insieme agli altri strumenti.
- 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.
- Tab distinti `Progetti` e `Salvataggio`: il primo gestisce archivio e opzioni live di visualizzazione, il secondo esporta selettivamente l'intera mappa in GeoJSON, KML o KMZ.
- Ogni progetto salva file GIS, POI, disegni, traccia, inquadratura e tutte le opzioni di visualizzazione: sfondo, layer catastali, trasparenza, misure, foglio importato, barra strumenti e preferenze GPS.
- GPS nativo MAUI ad alta precisione con permessi Android/iOS.
- Centratura automatica una tantum all'apertura: prima tramite posizione approssimativa della connessione Internet, poi tramite singola lettura GPS se la rete non restituisce una posizione; nessun punto o cerchio viene mostrato e il tracking continuo non viene avviato.
- 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, Salvataggio 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.
- Catalogo dei Comuni incluso nell'APK e cataloghi regionali OnData scaricati in cache solo quando servono.
- Ricerca catastale eseguita dal codice .NET nativo, senza DuckDB WebAssembly nella WebView Android.
- La registrazione della traccia GPS e' disattivata all'avvio; la toolbar di disegno puo' essere mostrata o nascosta dal tab Progetti.
- La registrazione della traccia GPS e' disattivata all'avvio; la toolbar di disegno completa puo' essere mostrata o nascosta dal tab Dati.
- Pannello `Layer` accessibile direttamente dalla mappa, con checkbox sincronizzati per confini, numeri particella, fogli, fabbricati, strade e acque.
- Le particelle cercate possono essere aggiunte una dopo l'altra, mantenendo contemporaneamente sulla mappa tutti i confini selezionati.
- Comandi separati per rimuovere le particelle selezionate o pulire importazioni, disegni, POI e traccia GPS.
+1 -1
View File
@@ -13,7 +13,7 @@ public sealed class AzureMapsService
public AzureMapsService()
{
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LMEMappeCatastali/0.2.8");
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LMEMappeCatastali/0.2.16");
_httpClient.DefaultRequestHeaders.Accept.ParseAdd("application/json");
}
+231
View File
@@ -0,0 +1,231 @@
using System.Globalization;
using System.IO.Compression;
using System.Text;
using System.Text.Json;
using System.Xml.Linq;
namespace LMEMappeCatastaliApp.Services;
public sealed class MapExportService
{
private static readonly XNamespace Kml = "http://www.opengis.net/kml/2.2";
public async Task<MapExportFile> CreateAsync(
string requestedName,
string requestedFormat,
string geoJson,
CancellationToken cancellationToken = default)
{
using var document = JsonDocument.Parse(geoJson);
var root = document.RootElement;
if (!root.TryGetProperty("type", out var type) || type.GetString() != "FeatureCollection"
|| !root.TryGetProperty("features", out var features)
|| features.ValueKind != JsonValueKind.Array)
{
throw new InvalidDataException("I dati raccolti dalla mappa non sono validi.");
}
var featureCount = features.GetArrayLength();
if (featureCount == 0)
{
throw new InvalidOperationException("Nessun oggetto selezionato e disponibile da esportare.");
}
var format = requestedFormat.Trim().ToLowerInvariant() switch
{
"kml" => "kml",
"kmz" => "kmz",
_ => "geojson"
};
var baseName = NormalizeFileName(requestedName);
var exportDirectory = Path.Combine(FileSystem.CacheDirectory, "Exports");
Directory.CreateDirectory(exportDirectory);
var path = Path.Combine(exportDirectory, $"{baseName}.{format}");
if (format == "geojson")
{
using var output = File.Create(path);
await JsonSerializer.SerializeAsync(output, root, new JsonSerializerOptions { WriteIndented = true }, cancellationToken);
return new(path, "application/geo+json", featureCount, Path.GetFileName(path));
}
var kml = BuildKml(features, baseName);
if (format == "kml")
{
await File.WriteAllTextAsync(path, kml, new UTF8Encoding(false), cancellationToken);
return new(path, "application/vnd.google-earth.kml+xml", featureCount, Path.GetFileName(path));
}
await using (var output = File.Create(path))
using (var archive = new ZipArchive(output, ZipArchiveMode.Create))
{
var entry = archive.CreateEntry("doc.kml", CompressionLevel.Optimal);
await using var entryStream = entry.Open();
await using var writer = new StreamWriter(entryStream, new UTF8Encoding(false));
await writer.WriteAsync(kml.AsMemory(), cancellationToken);
}
return new(path, "application/vnd.google-earth.kmz", featureCount, Path.GetFileName(path));
}
private static string BuildKml(JsonElement features, string documentName)
{
var document = new XElement(Kml + "Document",
new XElement(Kml + "name", documentName),
BuildStyle("imported", "ff2ecc71", "402ecc71"),
BuildStyle("imported-sheet", "ff22803d", "1022803d"),
BuildStyle("cadastral", "ff4444ef", "4224bffb"),
BuildStyle("cadastral-gps", "ffff7a00", "337aff00"),
BuildStyle("drawing", "ff1679f9", "333c92fb"),
BuildStyle("poi", "ffff7a00", "33ff7a00"),
BuildStyle("gps-trail", "ff00a5ff", "2200a5ff"));
foreach (var feature in features.EnumerateArray())
{
if (!feature.TryGetProperty("geometry", out var geometry)
|| geometry.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined)
{
continue;
}
var properties = feature.TryGetProperty("properties", out var propertyElement)
&& propertyElement.ValueKind == JsonValueKind.Object
? propertyElement
: default;
var category = GetString(properties, "_lmeCategory") ?? "drawing";
var placemark = new XElement(Kml + "Placemark",
new XElement(Kml + "name", FeatureName(properties, category)),
new XElement(Kml + "styleUrl", $"#{NormalizeStyleId(category)}"));
var extendedData = BuildExtendedData(properties);
if (extendedData is not null)
{
placemark.Add(extendedData);
}
placemark.Add(BuildGeometry(geometry));
document.Add(placemark);
}
return new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement(Kml + "kml", document)).ToString();
}
private static XElement BuildStyle(string id, string lineColor, string fillColor) =>
new(Kml + "Style",
new XAttribute("id", id),
new XElement(Kml + "LineStyle",
new XElement(Kml + "color", lineColor),
new XElement(Kml + "width", 3)),
new XElement(Kml + "PolyStyle", new XElement(Kml + "color", fillColor)));
private static XElement? BuildExtendedData(JsonElement properties)
{
if (properties.ValueKind != JsonValueKind.Object)
{
return null;
}
var data = properties.EnumerateObject()
.Where(item => item.Name != "_lmeCategory"
&& item.Value.ValueKind is JsonValueKind.String or JsonValueKind.Number or JsonValueKind.True or JsonValueKind.False)
.Select(item => new XElement(Kml + "Data",
new XAttribute("name", item.Name),
new XElement(Kml + "value", ScalarText(item.Value))))
.ToArray();
return data.Length == 0 ? null : new XElement(Kml + "ExtendedData", data);
}
private static XElement BuildGeometry(JsonElement geometry)
{
var type = geometry.GetProperty("type").GetString();
if (type == "GeometryCollection")
{
return new XElement(Kml + "MultiGeometry",
geometry.GetProperty("geometries").EnumerateArray().Select(BuildGeometry));
}
var coordinates = geometry.GetProperty("coordinates");
return type switch
{
"Point" => new XElement(Kml + "Point", CoordinatesElement([coordinates])),
"LineString" => new XElement(Kml + "LineString", CoordinatesElement(coordinates.EnumerateArray())),
"Polygon" => BuildPolygon(coordinates),
"MultiPoint" => new XElement(Kml + "MultiGeometry",
coordinates.EnumerateArray().Select(point => new XElement(Kml + "Point", CoordinatesElement([point])))),
"MultiLineString" => new XElement(Kml + "MultiGeometry",
coordinates.EnumerateArray().Select(line => new XElement(Kml + "LineString", CoordinatesElement(line.EnumerateArray())))),
"MultiPolygon" => new XElement(Kml + "MultiGeometry", coordinates.EnumerateArray().Select(BuildPolygon)),
_ => throw new InvalidDataException($"Geometria GeoJSON non supportata: {type}.")
};
}
private static XElement BuildPolygon(JsonElement rings)
{
var ringList = rings.EnumerateArray().ToArray();
var polygon = new XElement(Kml + "Polygon");
if (ringList.Length > 0)
{
polygon.Add(new XElement(Kml + "outerBoundaryIs",
new XElement(Kml + "LinearRing", CoordinatesElement(ringList[0].EnumerateArray()))));
}
foreach (var ring in ringList.Skip(1))
{
polygon.Add(new XElement(Kml + "innerBoundaryIs",
new XElement(Kml + "LinearRing", CoordinatesElement(ring.EnumerateArray()))));
}
return polygon;
}
private static XElement CoordinatesElement(IEnumerable<JsonElement> points) =>
new(Kml + "coordinates", string.Join(" ", points.Select(FormatCoordinate)));
private static string FormatCoordinate(JsonElement coordinate)
{
var values = coordinate.EnumerateArray().Take(3)
.Select(value => value.GetDouble().ToString("G17", CultureInfo.InvariantCulture));
return string.Join(",", values);
}
private static string FeatureName(JsonElement properties, string category) =>
GetString(properties, "name")
?? GetString(properties, "Name")
?? GetString(properties, "LABEL")
?? GetString(properties, "NATIONALCADASTRALREFERENCE")
?? category switch
{
"imported-sheet" => "Cornice o foglio importato",
"cadastral" => "Particella catastale",
"cadastral-gps" => "Particella GPS",
"poi" => "Punto di interesse",
"gps-trail" => "Traccia GPS",
_ => "Oggetto mappa"
};
private static string? GetString(JsonElement element, string name) =>
element.ValueKind == JsonValueKind.Object
&& element.TryGetProperty(name, out var value)
&& value.ValueKind == JsonValueKind.String
? value.GetString()
: null;
private static string ScalarText(JsonElement value) => value.ValueKind == JsonValueKind.String
? value.GetString() ?? string.Empty
: value.GetRawText();
private static string NormalizeStyleId(string category) => category switch
{
"imported" or "imported-sheet" or "cadastral" or "cadastral-gps" or "drawing" or "poi" or "gps-trail" => category,
_ => "drawing"
};
private static string NormalizeFileName(string requestedName)
{
var name = string.IsNullOrWhiteSpace(requestedName) ? "Mappa" : requestedName.Trim();
foreach (var invalid in Path.GetInvalidFileNameChars())
{
name = name.Replace(invalid, '_');
}
name = Path.GetFileNameWithoutExtension(name).Trim().TrimEnd('.');
return string.IsNullOrWhiteSpace(name) ? "Mappa" : name[..Math.Min(name.Length, 80)];
}
}
public sealed record MapExportFile(string Path, string MimeType, int FeatureCount, string FileName);
+74
View File
@@ -0,0 +1,74 @@
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using Microsoft.Maui.Networking;
namespace LMEMappeCatastaliApp.Services;
public sealed class NetworkLocationService
{
private readonly HttpClient httpClient = new()
{
Timeout = TimeSpan.FromSeconds(6)
};
public NetworkLocationService()
{
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LMEMappeCatastali/0.2.16");
}
public async Task<NetworkLocationSnapshot?> GetApproximateLocationAsync(
CancellationToken cancellationToken = default)
{
if (Connectivity.Current.NetworkAccess != NetworkAccess.Internet)
{
return null;
}
using var response = await httpClient.GetAsync("https://ipapi.co/json/", cancellationToken);
if (!response.IsSuccessStatusCode)
{
return null;
}
var result = await response.Content.ReadFromJsonAsync<IpLocationResponse>(cancellationToken);
if (result is null
|| result.Error == true
|| !result.Latitude.HasValue
|| !result.Longitude.HasValue
|| Math.Abs(result.Latitude.Value) > 90
|| Math.Abs(result.Longitude.Value) > 180)
{
return null;
}
var labelParts = new[] { result.City, result.Region, result.CountryName }
.Where(value => !string.IsNullOrWhiteSpace(value));
return new NetworkLocationSnapshot(
result.Latitude.Value,
result.Longitude.Value,
string.Join(", ", labelParts));
}
private sealed class IpLocationResponse
{
[JsonPropertyName("latitude")]
public double? Latitude { get; init; }
[JsonPropertyName("longitude")]
public double? Longitude { get; init; }
[JsonPropertyName("city")]
public string? City { get; init; }
[JsonPropertyName("region")]
public string? Region { get; init; }
[JsonPropertyName("country_name")]
public string? CountryName { get; init; }
[JsonPropertyName("error")]
public bool? Error { get; init; }
}
}
public sealed record NetworkLocationSnapshot(double Latitude, double Longitude, string Label);
+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(
+50 -3
View File
@@ -292,6 +292,20 @@ input[type="checkbox"] {
color: var(--ink);
}
.leaflet-top.leaflet-right {
top: 68px;
right: 2px;
}
.map-stage.search-active .leaflet-top.leaflet-right {
top: 136px;
}
.leaflet-touch .leaflet-draw-toolbar a {
width: 38px;
height: 38px;
}
.tool-sheet {
position: absolute;
top: 0;
@@ -358,6 +372,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;
@@ -637,7 +674,7 @@ label {
left: 0;
z-index: 1200;
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
grid-template-columns: repeat(6, minmax(0, 1fr));
height: var(--nav-height);
padding-bottom: env(safe-area-inset-bottom);
border-top: 1px solid #bcc7cd;
@@ -738,6 +775,15 @@ footer {
top: 136px;
}
.leaflet-top.leaflet-right {
top: 122px;
right: 0;
}
.map-stage.search-active .leaflet-top.leaflet-right {
top: 190px;
}
.gps-main,
.gps-center {
padding: 0 8px;
@@ -755,7 +801,8 @@ footer {
}
.bottom-tabs button {
font-size: 11px;
padding: 0 2px;
font-size: 10px;
}
.wms-preview {
@@ -777,6 +824,6 @@ footer {
}
.bottom-tabs button {
font-size: 10px;
font-size: 9px;
}
}
+614 -105
View File
@@ -7,18 +7,23 @@ 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,
drawControl: null,
activeDrawHandler: null,
drawEventsBound: false,
importParcelOnly: true,
includeKmlSheetLayer: false,
showImportedMeasurements: false,
showDrawingMeasurements: true,
measurementRefreshTimer: null,
gpsMarker: null,
gpsAccuracy: null,
gpsPositionVisible: true,
hasLiveGpsFix: false,
lastAccuracy: 0,
gpsTrail: null,
selectedParcelsLayer: null,
gpsParcelLayer: null,
@@ -40,6 +45,7 @@ const cadastreCrs = L.extend({}, L.CRS.EPSG4326, { code: "EPSG:4258" });
window.lmeMap = {
init,
showSearchResult,
showInitialPosition,
displayOfficialParcel,
exportCadastreView,
closeCadastrePreview,
@@ -47,13 +53,15 @@ window.lmeMap = {
clearMapElements,
fitImported,
clearImported,
setImportParcelOnly,
setIncludeKmlSheetLayer,
setImportedSheetLayerVisible,
setImportedMeasurementsVisible,
setDrawingMeasurementsVisible,
addProjectMarker,
startMeasurementDrawing,
setDrawToolsVisible,
clearDrawings,
createMapExportGeoJson,
createProjectSnapshot,
loadProjectSnapshot,
getLegacyProjectSnapshot,
@@ -69,6 +77,7 @@ window.lmeMap = {
centerOnGps,
toggleTrail,
setNativeGpsPosition,
setGpsPositionVisible,
setGpsError,
resize,
showInfo: setInfo
@@ -123,7 +132,10 @@ function init() {
});
lmeState.currentBase = lmeState.baseLayers.satellite.addTo(lmeState.map);
const importedSheetPane = lmeState.map.createPane("importedSheetPane");
importedSheetPane.style.zIndex = "520";
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);
@@ -133,6 +145,7 @@ function init() {
refreshCadastreLayer();
bindFileImport();
bindDrawingEvents();
if (!lmeState.resizeBound) {
window.addEventListener("resize", resize);
@@ -178,6 +191,29 @@ function showSearchResult(latitude, longitude, label) {
setInfo(label || `${lat.toFixed(6)}, ${lon.toFixed(6)}`);
}
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];
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) {
const lat = Number(latitude);
const lon = Number(longitude);
@@ -435,22 +471,22 @@ function bindFileImport() {
try {
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 }),
onEachFeature: (feature, layer) => {
const name = feature?.properties?.name || file.name;
layer.bindPopup(`<strong>${escapeHtml(name)}</strong>`);
}
}).addTo(lmeState.imported);
fitLayer(layer);
const parcelLayer = addImportedFeatures(geojson);
const sheetGeojson = result.sheetGeojson || emptyFeatureCollection();
const sheetLayer = addImportedSheetFeatures(sheetGeojson);
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 non particella`
? `; 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}`);
@@ -575,7 +611,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) {
@@ -652,13 +693,22 @@ function normalizeKmlFiles(files) {
throw new Error("KML senza geometrie utilizzabili");
}
const selected = lmeState.importParcelOnly ? filterKmlParcelFeatures(features) : features;
if (!selected.length) {
throw new Error("nessuna particella trovata; disattiva 'solo particelle' per importare tutti gli elementi");
const polygonParts = splitKmlPolygonFeatures(features);
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: features.length - selected.length,
geojson: { type: "FeatureCollection", features: parcels },
sheetGeojson: {
type: "FeatureCollection",
features: lmeState.includeKmlSheetLayer ? optionalFeatures : []
},
ignoredCount: lmeState.includeKmlSheetLayer ? 0 : optionalFeatures.length,
reprojected: false
};
}
@@ -690,61 +740,116 @@ function kmlTextToGeoJson(text, sourceName) {
}
function filterKmlParcelFeatures(features) {
const polygons = features
.map(feature => ({ ...feature, geometry: polygonOnlyGeometry(feature.geometry) }))
.filter(feature => feature.geometry);
const filtered = polygons.filter(feature => {
const properties = feature.properties || {};
if (properties["@geometry-type"] === "groundoverlay") {
const filtered = features.filter(feature => {
if (isSheetOrOverlayFeature(feature)) {
return false;
}
const properties = feature.properties || {};
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[ _-]?foglio/.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 removeLikelySheetOutline(filtered);
return removeLikelySheetOutlines(filtered);
}
function polygonOnlyGeometry(geometry) {
if (!geometry) {
return null;
function isSheetOrOverlayFeature(feature) {
const properties = feature?.properties || {};
const geometryType = String(properties["@geometry-type"] || "").toLowerCase();
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(" ").toLowerCase();
if (geometryType === "groundoverlay" || /^doc[_ -]?\d+$/i.test(name)) {
return true;
}
if (geometry.type === "Polygon" || geometry.type === "MultiPolygon") {
return geometry;
const hasParcelNumber = /^[a-z]?\s*\d+[a-z]?(?:[\/. -]\d+[a-z]?)?$/i.test(name);
return !hasParcelNumber
&& /\bfoglio\b|\bsheet\b|quadro[ _-]?d[' ]?unione|(?:perimetro|bordo|limite|contorno)[ _-]?(?:del[ _-]?)?foglio|sheet[ _-]?boundary/.test(context);
}
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") {
const geometries = (geometry.geometries || []).filter(item =>
item.type === "Polygon" || item.type === "MultiPolygon");
return geometries.length ? { type: "GeometryCollection", geometries } : null;
(geometry.geometries || []).forEach((item, index) => addGeometry(feature, item, `${partIndex}.${index}`));
}
return null;
};
features.forEach((feature, index) => addGeometry(feature, feature.geometry, index));
return result;
}
function removeLikelySheetOutline(features) {
if (features.length < 3) {
return features;
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 candidates = features.map(feature => ({ feature, bounds: geoJsonBounds(feature.geometry) }));
const valid = candidates.filter(item => item.bounds);
if (valid.length < 3) {
return features;
}
const areas = valid.map(item => boundsArea(item.bounds)).sort((a, b) => a - b);
const median = areas[Math.floor(areas.length / 2)];
const largest = valid.reduce((current, item) =>
const largest = candidates.reduce((current, item) =>
boundsArea(item.bounds) > boundsArea(current.bounds) ? item : current);
const others = valid.filter(item => item !== largest);
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 looksLikeSheet = boundsArea(largest.bounds) > median * 8
&& contained >= Math.ceil(others.length * 0.75);
return looksLikeSheet ? features.filter(feature => feature !== largest.feature) : features;
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) {
@@ -774,11 +879,147 @@ function boundsContains(bounds, point) {
&& point[1] >= bounds.south && point[1] <= bounds.north;
}
function setImportParcelOnly(enabled) {
lmeState.importParcelOnly = Boolean(enabled);
setInfo(lmeState.importParcelOnly
? "Importazione KML/KMZ: verranno caricate solo le particelle."
: "Importazione KML/KMZ: verranno caricati tutti gli elementi.");
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 setImportedSheetLayerVisible(enabled) {
migrateMisclassifiedImportedSheets();
lmeState.importedSheetsVisible = Boolean(enabled);
const generated = lmeState.importedSheetsVisible && ensureImportedSheetOutline();
applyImportedSheetVisibility();
const count = lmeState.importedSheets?.toGeoJSON()?.features?.length || 0;
setInfo(lmeState.importedSheetsVisible
? (count
? `${generated ? "Cornice generata dai dati importati" : "Layer del foglio importato visibile"} (${count} elementi).`
: "Nessun dato importato da cui ricavare la cornice del foglio.")
: "Layer del foglio importato nascosto; le particelle restano visibili.");
}
function ensureImportedSheetOutline() {
if (!lmeState.imported || !lmeState.importedSheets) {
return false;
}
const currentSheets = lmeState.importedSheets.toGeoJSON();
const hasAreaOutline = (currentSheets.features || []).some(feature =>
["Polygon", "MultiPolygon"].includes(feature?.geometry?.type));
if (hasAreaOutline) {
return false;
}
const imported = lmeState.imported.toGeoJSON();
const points = collectGeoJsonCoordinates(imported);
if (!points.length) {
return false;
}
const bounds = points.reduce((result, point) => ({
west: Math.min(result.west, point[0]),
south: Math.min(result.south, point[1]),
east: Math.max(result.east, point[0]),
north: Math.max(result.north, point[1])
}), { west: Infinity, south: Infinity, east: -Infinity, north: -Infinity });
if (!Number.isFinite(bounds.west)
|| !Number.isFinite(bounds.south)
|| bounds.east <= bounds.west
|| bounds.north <= bounds.south) {
return false;
}
const longitudePadding = Math.max((bounds.east - bounds.west) * 0.01, 0.000001);
const latitudePadding = Math.max((bounds.north - bounds.south) * 0.01, 0.000001);
const west = bounds.west - longitudePadding;
const south = bounds.south - latitudePadding;
const east = bounds.east + longitudePadding;
const north = bounds.north + latitudePadding;
addImportedSheetFeatures({
type: "FeatureCollection",
features: [{
type: "Feature",
properties: {
name: "Cornice del foglio importato",
_lmeGeneratedSheetOutline: true
},
geometry: {
type: "Polygon",
coordinates: [[
[west, south],
[east, south],
[east, north],
[west, north],
[west, south]
]]
}
}]
});
return true;
}
function migrateMisclassifiedImportedSheets() {
if (!lmeState.imported || !lmeState.importedSheets) {
return 0;
}
const current = lmeState.imported.toGeoJSON();
const misplaced = (current.features || []).filter(isSheetOrOverlayFeature);
if (!misplaced.length) {
return 0;
}
const retained = (current.features || []).filter(feature => !isSheetOrOverlayFeature(feature));
lmeState.imported.clearLayers();
addImportedFeatures({ type: "FeatureCollection", features: retained });
addImportedSheetFeatures({ type: "FeatureCollection", features: misplaced });
refreshImportedMeasurements();
return misplaced.length;
}
function addImportedFeatures(geojson) {
return L.geoJSON(geojson || emptyFeatureCollection(), {
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: bindStoredFeaturePopup
}).addTo(lmeState.imported);
}
function addImportedSheetFeatures(geojson) {
return L.geoJSON(geojson || emptyFeatureCollection(), {
pane: "importedSheetPane",
style: { color: "#f59e0b", weight: 4, opacity: 1, fillOpacity: 0.03, dashArray: "10 6" },
pointToLayer: (feature, latlng) => L.circleMarker(latlng, {
pane: "importedSheetPane",
radius: 7,
color: "#f59e0b",
fillColor: "#ffffff",
fillOpacity: 0.85
}),
onEachFeature: bindStoredFeaturePopup
}).addTo(lmeState.importedSheets);
}
function applyImportedSheetVisibility() {
if (!lmeState.map || !lmeState.importedSheets) {
return;
}
if (lmeState.importedSheetsVisible) {
if (!lmeState.map.hasLayer(lmeState.importedSheets)) {
lmeState.importedSheets.addTo(lmeState.map);
}
lmeState.importedSheets.bringToFront();
return;
}
if (lmeState.map.hasLayer(lmeState.importedSheets)) {
lmeState.map.removeLayer(lmeState.importedSheets);
}
}
function setImportedMeasurementsVisible(enabled) {
@@ -798,11 +1039,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();
@@ -821,26 +1069,27 @@ function addProjectMarker(name) {
setInfo(`POI aggiunto: ${label}`);
}
function enableDrawTools() {
if (lmeState.drawControl) {
setInfo("Strumenti di disegno gia attivi.");
return;
function configureDrawLabels() {
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.";
}
lmeState.drawControl = new L.Control.Draw({
position: "topright",
edit: { featureGroup: lmeState.drawings },
draw: {
circle: { metric: true, feet: false },
circlemarker: false,
marker: true,
polygon: { metric: true, feet: false, showArea: true, allowIntersection: false },
polyline: { metric: true, feet: false, showLength: true },
rectangle: true
function bindDrawingEvents() {
if (!lmeState.map || lmeState.drawEventsBound) {
return;
}
});
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);
@@ -869,17 +1118,48 @@ function enableDrawTools() {
});
lmeState.drawEventsBound = true;
}
setInfo("Disegno attivo: crea POI, linee e aree sulla mappa.");
function enableDrawTools() {
if (lmeState.drawControl) {
setInfo("Strumenti di disegno gia attivi.");
return;
}
configureDrawLabels();
const orangeArea = { color: "#f97316", weight: 4, fillColor: "#fb923c", fillOpacity: 0.2 };
lmeState.drawControl = new L.Control.Draw({
position: "topright",
edit: { featureGroup: lmeState.drawings },
draw: {
circle: { metric: true, feet: false, showRadius: true, shapeOptions: orangeArea },
circlemarker: false,
marker: true,
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: { metric: true, shapeOptions: orangeArea }
}
});
lmeState.map.addControl(lmeState.drawControl);
bindDrawingEvents();
setInfo("Barra strumenti attiva: misure, disegni, POI, modifica e cancellazione.");
}
function startMeasurementDrawing(mode) {
if (!lmeState.map) {
return;
}
if (!lmeState.drawEventsBound) {
enableDrawTools();
setDrawToolsVisible(false);
}
bindDrawingEvents();
if (lmeState.activeDrawHandler) {
lmeState.activeDrawHandler.disable();
}
@@ -1196,10 +1476,89 @@ function formatNumber(value, digits) {
}).format(value);
}
function createMapExportGeoJson(options) {
migrateMisclassifiedImportedSheets();
const requested = options || {};
const features = [];
if (requested.includeImported !== false) {
appendExportFeatures(features, lmeState.imported?.toGeoJSON(), "imported");
}
if (requested.includeImportedSheets !== false) {
appendExportFeatures(features, lmeState.importedSheets?.toGeoJSON(), "imported-sheet");
}
if (requested.includeCadastral !== false) {
appendExportFeatures(features, lmeState.selectedParcelsLayer?.toGeoJSON(), "cadastral");
appendExportFeatures(features, lmeState.gpsParcelLayer?.toGeoJSON(), "cadastral-gps");
}
const drawings = lmeState.drawings?.toGeoJSON() || emptyFeatureCollection();
if (requested.includeDrawings !== false) {
appendExportFeatures(features, drawings, "drawing", feature => !isPoiFeature(feature));
}
if (requested.includePoi !== false) {
appendExportFeatures(features, drawings, "poi", isPoiFeature);
}
if (requested.includeTrail !== false && lmeState.gpsTrailPoints.length >= 2) {
features.push({
type: "Feature",
properties: { name: "Traccia GPS", _lmeCategory: "gps-trail" },
geometry: {
type: "LineString",
coordinates: lmeState.gpsTrailPoints.map(point => [
Number(point.lng ?? point[1]),
Number(point.lat ?? point[0])
])
}
});
}
return JSON.stringify({ type: "FeatureCollection", features });
}
function appendExportFeatures(target, collection, category, predicate = () => true) {
for (const sourceFeature of collection?.features || []) {
if (!sourceFeature?.geometry || !predicate(sourceFeature)) {
continue;
}
const feature = JSON.parse(JSON.stringify(sourceFeature));
feature.properties = { ...(feature.properties || {}), _lmeCategory: category };
if (feature.properties._lmeShape === "circle"
&& feature.geometry.type === "Point"
&& Number(feature.properties._lmeRadius) > 0) {
feature.geometry = circleToPolygon(feature.geometry.coordinates, Number(feature.properties._lmeRadius));
}
target.push(feature);
}
}
function isPoiFeature(feature) {
return feature?.geometry?.type === "Point"
&& feature?.properties?._lmeShape !== "circle";
}
function circleToPolygon(center, radiusMeters) {
const longitude = Number(center?.[0]);
const latitude = Number(center?.[1]);
const earthRadius = 6378137;
const latitudeRadians = latitude * Math.PI / 180;
const ring = [];
for (let index = 0; index <= 64; index += 1) {
const angle = index / 64 * Math.PI * 2;
const north = Math.sin(angle) * radiusMeters;
const east = Math.cos(angle) * radiusMeters;
ring.push([
longitude + east / (earthRadius * Math.cos(latitudeRadians)) * 180 / Math.PI,
latitude + north / earthRadius * 180 / Math.PI
]);
}
return { type: "Polygon", coordinates: [ring] };
}
function createProjectSnapshot(includeCadastralParcels) {
const center = lmeState.map.getCenter();
return JSON.stringify({
schemaVersion: 1,
schemaVersion: 3,
view: {
latitude: center.lat,
longitude: center.lng,
@@ -1207,6 +1566,9 @@ function createProjectSnapshot(includeCadastralParcels) {
},
drawings: lmeState.drawings.toGeoJSON(),
imported: lmeState.imported.toGeoJSON(),
importedSheets: lmeState.importedSheets.toGeoJSON(),
importedSheetsVisible: lmeState.importedSheetsVisible,
displayOptions: captureDisplayOptions(),
selectedParcels: includeCadastralParcels
? lmeState.selectedParcelsLayer.toGeoJSON()
: { type: "FeatureCollection", features: [] },
@@ -1234,6 +1596,7 @@ function loadProjectSnapshot(raw, projectName) {
lmeState.drawings.clearLayers();
lmeState.imported.clearLayers();
lmeState.importedSheets.clearLayers();
lmeState.drawingMeasurements.clearLayers();
lmeState.importedMeasurements.clearLayers();
lmeState.selectedParcelsLayer.clearLayers();
@@ -1257,16 +1620,21 @@ function loadProjectSnapshot(raw, projectName) {
onEachFeature: bindStoredFeaturePopup
});
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, {
radius: 7,
color: "#22c55e",
fillColor: "#ffffff",
fillOpacity: 0.9
}),
onEachFeature: bindStoredFeaturePopup
}).addTo(lmeState.imported);
const importedParts = partitionStoredImportedFeatures(
data.imported || emptyFeatureCollection(),
data.importedSheets || emptyFeatureCollection());
addImportedFeatures(importedParts.parcels);
addImportedSheetFeatures(importedParts.sheets);
const projectDisplayOptions = data.schemaVersion >= 3 && data.displayOptions
? data.displayOptions
: null;
lmeState.importedSheetsVisible = projectDisplayOptions
? Boolean(projectDisplayOptions.importedSheetsVisible)
: data.schemaVersion >= 2 && Boolean(data.importedSheetsVisible);
if (lmeState.importedSheetsVisible) {
ensureImportedSheetOutline();
}
applyImportedSheetVisibility();
L.geoJSON(data.selectedParcels || emptyFeatureCollection(), {
style: { color: "#ef4444", weight: 4, opacity: 1, fillColor: "#fbbf24", fillOpacity: 0.26 },
onEachFeature: (feature, layer) => {
@@ -1282,15 +1650,22 @@ function loadProjectSnapshot(raw, projectName) {
lmeState.gpsTrailPoints = Array.isArray(data.trail) ? data.trail : [];
lmeState.gpsTrail.setLatLngs(lmeState.gpsTrailPoints);
if (projectDisplayOptions) {
applyProjectDisplayOptions(projectDisplayOptions);
}
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)
@@ -1304,13 +1679,99 @@ 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 captureDisplayOptions();
} catch (error) {
setInfo(`Progetto non leggibile: ${error.message}`);
throw error;
}
}
function captureDisplayOptions() {
return {
baseLayer: lmeState.currentBaseName,
cadastreOpacity: lmeState.cadastreOpacity,
cadastreLayers: [...lmeState.cadastreLayers],
includeKmlSheetLayer: lmeState.includeKmlSheetLayer,
importedSheetsVisible: lmeState.importedSheetsVisible,
showImportedMeasurements: lmeState.showImportedMeasurements,
showDrawingMeasurements: lmeState.showDrawingMeasurements,
drawToolsVisible: Boolean(lmeState.drawControl),
gpsPositionVisible: lmeState.gpsPositionVisible,
trailEnabled: lmeState.gpsTrailEnabled
};
}
function applyProjectDisplayOptions(options) {
const supportedCadastreLayers = new Set([
"CP.CadastralParcel",
"codice_plla",
"CP.CadastralZoning",
"fabbricati",
"strade",
"acque"
]);
if (Array.isArray(options.cadastreLayers)) {
lmeState.cadastreLayers = options.cadastreLayers.filter(layer => supportedCadastreLayers.has(layer));
}
const opacity = Number(options.cadastreOpacity);
if (Number.isFinite(opacity)) {
lmeState.cadastreOpacity = Math.max(0, Math.min(1, opacity));
}
lmeState.includeKmlSheetLayer = Boolean(options.includeKmlSheetLayer);
lmeState.importedSheetsVisible = Boolean(options.importedSheetsVisible);
lmeState.showImportedMeasurements = Boolean(options.showImportedMeasurements);
lmeState.showDrawingMeasurements = options.showDrawingMeasurements !== false;
applyImportedSheetVisibility();
refreshCadastreLayer();
if (typeof options.baseLayer === "string") {
setBaseLayer(options.baseLayer);
}
setGpsPositionVisible(options.gpsPositionVisible !== false);
toggleTrail(Boolean(options.trailEnabled));
setDrawToolsVisible(Boolean(options.drawToolsVisible));
}
function partitionStoredImportedFeatures(imported, storedSheets) {
const parcelFeatures = [];
const sheetFeatures = [...(storedSheets?.features || [])];
const sourceGroups = new Map();
(imported?.features || []).forEach(feature => {
if (isSheetOrOverlayFeature(feature)) {
sheetFeatures.push(feature);
return;
}
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: [] };
}
@@ -1514,7 +1975,11 @@ function htmlToText(value) {
}
function setCadastreOpacity(value) {
lmeState.cadastreOpacity = Number(value || 0.75);
const opacity = Number(value);
if (!Number.isFinite(opacity)) {
return;
}
lmeState.cadastreOpacity = Math.max(0, Math.min(1, opacity));
if (lmeState.cadastre) {
lmeState.cadastre.setOpacity(lmeState.cadastreOpacity);
}
@@ -1605,6 +2070,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) {
@@ -1618,6 +2084,7 @@ function clearMapElements() {
lmeState.selectedParcelsLayer.clearLayers();
lmeState.gpsParcelLayer.clearLayers();
lmeState.imported.clearLayers();
lmeState.importedSheets.clearLayers();
lmeState.drawings.clearLayers();
lmeState.importedMeasurements.clearLayers();
lmeState.drawingMeasurements.clearLayers();
@@ -1671,6 +2138,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.");
@@ -1695,14 +2181,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) {
@@ -1710,10 +2194,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.");