Compare commits

...
2 Commits
Author SHA1 Message Date
livio 78af860493 Fix KMZ overlays and add map export 2026-09-22 08:43:23 +02:00
livio 32a36c98ec Persist project display options and toggle map tools 2026-09-21 14:27:45 +02:00
8 changed files with 668 additions and 77 deletions

No files matched your search

+189 -7
View File
@@ -7,6 +7,7 @@
@inject NetworkLocationService NetworkLocationService @inject NetworkLocationService NetworkLocationService
@inject AzureMapsService AzureMapsService @inject AzureMapsService AzureMapsService
@inject ProjectStorageService ProjectStorageService @inject ProjectStorageService ProjectStorageService
@inject MapExportService MapExportService
@implements IAsyncDisposable @implements IAsyncDisposable
<PageTitle>LME Mappe Catastali</PageTitle> <PageTitle>LME Mappe Catastali</PageTitle>
@@ -190,7 +191,7 @@
<span>Mostra superficie, perimetro e lati</span> <span>Mostra superficie, perimetro e lati</span>
</label> </label>
<button class="secondary-command" aria-pressed="@DrawToolsVisible" @onclick="ToggleDrawTools"> <button class="secondary-command" aria-pressed="@DrawToolsVisible" @onclick="ToggleDrawTools">
@(DrawToolsVisible ? "Nascondi barra completa" : "Mostra barra completa") @(DrawToolsVisible ? "Nascondi strumenti sulla mappa" : "Mostra strumenti sulla mappa")
</button> </button>
<button class="danger-command" @onclick="ClearDrawings">Elimina disegni e POI</button> <button class="danger-command" @onclick="ClearDrawings">Elimina disegni e POI</button>
</section> </section>
@@ -208,6 +209,52 @@
else if (ActiveTab == "projects") else if (ActiveTab == "projects")
{ {
<section class="panel-content"> <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 class="panel-section"> <section class="panel-section">
<h2>Salva progetto</h2> <h2>Salva progetto</h2>
<label> <label>
@@ -263,7 +310,7 @@
</label> </label>
<label> <label>
Trasparenza catasto Trasparenza catasto
<input type="range" min="0" max="1" step="0.05" value="0.75" @onchange="ChangeCadastreOpacity" /> <input type="range" min="0" max="1" step="0.05" value="@CadastralOpacity.ToString(System.Globalization.CultureInfo.InvariantCulture)" @onchange="ChangeCadastreOpacity" />
</label> </label>
</section> </section>
@@ -338,7 +385,7 @@
<button class="@(ActiveTab == "map" || ActiveTab == "search" ? "active" : null)" @onclick='() => SelectTab("map")'>Mappa</button> <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 == "cadastre" ? "active" : null)" @onclick='() => SelectTab("cadastre")'>Catasto</button>
<button class="@(ActiveTab == "data" ? "active" : null)" @onclick='() => SelectTab("data")'>Dati</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 == "projects" ? "active" : null)" @onclick='() => SelectTab("projects")'>Salvataggio</button>
<button class="@(ActiveTab == "settings" ? "active" : null)" @onclick='() => SelectTab("settings")'>Impostazioni</button> <button class="@(ActiveTab == "settings" ? "active" : null)" @onclick='() => SelectTab("settings")'>Impostazioni</button>
</nav> </nav>
</section> </section>
@@ -348,6 +395,8 @@
private string ActiveTab { get; set; } = "map"; private string ActiveTab { get; set; } = "map";
private string SearchText { get; set; } = string.Empty; private string SearchText { get; set; } = string.Empty;
private string NewProjectName { 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 PoiName { get; set; } = string.Empty;
private string SelectedProjectId { get; set; } = string.Empty; private string SelectedProjectId { get; set; } = string.Empty;
private string ProjectArchiveMessage { get; set; } = "Nessun progetto salvato."; private string ProjectArchiveMessage { get; set; } = "Nessun progetto salvato.";
@@ -361,6 +410,7 @@
private string SelectedParcelNumber { get; set; } = string.Empty; private string SelectedParcelNumber { get; set; } = string.Empty;
private string CatalogMessage { get; set; } = string.Empty; private string CatalogMessage { get; set; } = string.Empty;
private double? CatalogFraction { get; set; } private double? CatalogFraction { get; set; }
private double CadastralOpacity { get; set; } = 0.75;
private bool CatalogBusy { get; set; } private bool CatalogBusy { get; set; }
private bool GpsActive { get; set; } private bool GpsActive { get; set; }
private bool ShowGpsPosition { get; set; } = true; private bool ShowGpsPosition { get; set; } = true;
@@ -373,6 +423,13 @@
private bool ShowImportedMeasurements { get; set; } private bool ShowImportedMeasurements { get; set; }
private bool ShowDrawingMeasurements { get; set; } = true; private bool ShowDrawingMeasurements { get; set; } = true;
private bool ProjectBusy { get; set; } 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? CatalogCancellation { get; set; }
private CancellationTokenSource? GpsLookupCancellation { get; set; } private CancellationTokenSource? GpsLookupCancellation { get; set; }
private long LastGpsLookupAt; private long LastGpsLookupAt;
@@ -394,7 +451,7 @@
{ {
"cadastre" => "Ricerca catastale", "cadastre" => "Ricerca catastale",
"data" => "Dati e disegni", "data" => "Dati e disegni",
"projects" => "Archivio progetti", "projects" => "Salvataggio ed esportazione",
"settings" => "Impostazioni", "settings" => "Impostazioni",
_ => string.Empty _ => string.Empty
}; };
@@ -403,7 +460,7 @@
{ {
"cadastre" => "Regione, Comune, Foglio, Particella", "cadastre" => "Regione, Comune, Foglio, Particella",
"data" => "File GIS, misure e POI", "data" => "File GIS, misure e POI",
"projects" => "Salva e apri i tuoi lavori", "projects" => "Progetti e file GIS",
"settings" => "Mappa, GPS e servizi ufficiali", "settings" => "Mappa, GPS e servizi ufficiali",
_ => string.Empty _ => string.Empty
}; };
@@ -460,6 +517,43 @@
} }
} }
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() private async Task CenterOnInitialLocationAsync()
{ {
NetworkLocationSnapshot? networkLocation = null; NetworkLocationSnapshot? networkLocation = null;
@@ -918,6 +1012,47 @@
return Task.CompletedTask; 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() private async Task SaveProject()
{ {
var name = NewProjectName.Trim(); var name = NewProjectName.Trim();
@@ -976,8 +1111,11 @@
try try
{ {
var snapshot = await ProjectStorageService.LoadAsync(project.Id); var snapshot = await ProjectStorageService.LoadAsync(project.Id);
ShowImportedSheetLayer = await JS.InvokeAsync<bool>("lmeMap.loadProjectSnapshot", snapshot, project.Name); await ConfigureProjectMapProviderAsync(snapshot);
var displayOptions = await JS.InvokeAsync<ProjectDisplayOptions>("lmeMap.loadProjectSnapshot", snapshot, project.Name);
ApplyProjectDisplayOptions(displayOptions);
NewProjectName = project.Name; NewProjectName = project.Name;
ExportFileName = project.Name;
IncludeCadastralParcels = project.IncludesCadastralParcels; IncludeCadastralParcels = project.IncludesCadastralParcels;
ActiveTab = "map"; ActiveTab = "map";
await Task.Delay(30); await Task.Delay(30);
@@ -993,6 +1131,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() private async Task DeleteProject()
{ {
var project = Projects.FirstOrDefault(item => item.Id == SelectedProjectId); var project = Projects.FirstOrDefault(item => item.Id == SelectedProjectId);
@@ -1114,7 +1271,18 @@
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Chiave Azure Maps non salvata: {error.GetBaseException().Message}"); 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) private async Task ToggleCadastreLayer(CadastralLayer layer, ChangeEventArgs args)
{ {
@@ -1149,6 +1317,20 @@
public string Detail { get; } = detail; 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() public ValueTask DisposeAsync()
{ {
CancelCatalogWork(); CancelCatalogWork();
+2 -2
View File
@@ -28,8 +28,8 @@
<ApplicationId>com.companyname.lmemappecatastaliapp</ApplicationId> <ApplicationId>com.companyname.lmemappecatastaliapp</ApplicationId>
<!-- Versions --> <!-- Versions -->
<ApplicationDisplayVersion>0.2.11</ApplicationDisplayVersion> <ApplicationDisplayVersion>0.2.13</ApplicationDisplayVersion>
<ApplicationVersion>15</ApplicationVersion> <ApplicationVersion>17</ApplicationVersion>
<!-- To develop, package, and publish an app to the Microsoft Store, see: https://aka.ms/MauiTemplateUnpackaged --> <!-- To develop, package, and publish an app to the Microsoft Store, see: https://aka.ms/MauiTemplateUnpackaged -->
<WindowsPackageType>None</WindowsPackageType> <WindowsPackageType>None</WindowsPackageType>
+1
View File
@@ -23,6 +23,7 @@ public static class MauiProgram
builder.Services.AddSingleton<NetworkLocationService>(); builder.Services.AddSingleton<NetworkLocationService>();
builder.Services.AddSingleton<AzureMapsService>(); builder.Services.AddSingleton<AzureMapsService>();
builder.Services.AddSingleton<ProjectStorageService>(); builder.Services.AddSingleton<ProjectStorageService>();
builder.Services.AddSingleton<MapExportService>();
#if DEBUG #if DEBUG
builder.Services.AddBlazorWebViewDeveloperTools(); builder.Services.AddBlazorWebViewDeveloperTools();
+5 -3
View File
@@ -11,20 +11,22 @@ App .NET MAUI Blazor Hybrid per Android, iOS, Mac Catalyst e Windows, pensata pe
- Import di file KML, KMZ, GeoJSON e JSON. - Import di file KML, KMZ, GeoJSON e JSON.
- Import GeoJSON compatibile con BOM, geometrie singole, array, FeatureCollection e coordinate Web Mercator EPSG:3857. - 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 e puo essere mostrato o nascosto separatamente. - 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. - Inquadramento e pulizia dei layer importati.
- Disegno di marker, linee, poligoni e rettangoli. - Disegno di marker, linee, poligoni e rettangoli.
- Area, Distanza e Cerchio disponibili nella barra Leaflet laterale direttamente sulla mappa, 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. - 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. - 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. - 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 e il foglio KML/KMZ mantiene la propria visibilita separata. - Tab `Salvataggio` con esportazione selettiva dell'intera mappa in GeoJSON, KML o KMZ: dati importati, cornici/fogli, particelle catastali rosse, disegni, cerchi, POI e traccia GPS.
- 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. - 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. - 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. - 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. - Marker posizione, cerchio accuratezza in metri, tracciamento percorso.
- Controllo se la posizione GPS cade dentro un poligono importato o disegnato. - 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. - 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 separati Catasto, Dati, 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". - Ingrandimento oltre lo zoom satellitare nativo senza tessere "Map data not yet available".
- Tendine concatenate Regione, Comune, Foglio e Particella. - Tendine concatenate Regione, Comune, Foglio e Particella.
- Ricerca di localita e indirizzi eseguita nativamente con fallback Esri e OpenStreetMap, senza richieste CORS dalla WebView. - 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() public AzureMapsService()
{ {
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LMEMappeCatastali/0.2.11"); _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LMEMappeCatastali/0.2.13");
_httpClient.DefaultRequestHeaders.Accept.ParseAdd("application/json"); _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);
+1 -1
View File
@@ -13,7 +13,7 @@ public sealed class NetworkLocationService
public NetworkLocationService() public NetworkLocationService()
{ {
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LMEMappeCatastali/0.2.11"); httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LMEMappeCatastali/0.2.13");
} }
public async Task<NetworkLocationSnapshot?> GetApproximateLocationAsync( public async Task<NetworkLocationSnapshot?> GetApproximateLocationAsync(
+238 -63
View File
@@ -12,7 +12,6 @@ const lmeState = {
importedMeasurements: null, importedMeasurements: null,
drawings: null, drawings: null,
drawingMeasurements: null, drawingMeasurements: null,
quickMeasureControl: null,
drawControl: null, drawControl: null,
activeDrawHandler: null, activeDrawHandler: null,
drawEventsBound: false, drawEventsBound: false,
@@ -62,6 +61,7 @@ window.lmeMap = {
startMeasurementDrawing, startMeasurementDrawing,
setDrawToolsVisible, setDrawToolsVisible,
clearDrawings, clearDrawings,
createMapExportGeoJson,
createProjectSnapshot, createProjectSnapshot,
loadProjectSnapshot, loadProjectSnapshot,
getLegacyProjectSnapshot, getLegacyProjectSnapshot,
@@ -144,7 +144,6 @@ function init() {
refreshCadastreLayer(); refreshCadastreLayer();
bindFileImport(); bindFileImport();
bindDrawingEvents(); bindDrawingEvents();
addQuickMeasureControl();
if (!lmeState.resizeBound) { if (!lmeState.resizeBound) {
window.addEventListener("resize", resize); window.addEventListener("resize", resize);
@@ -754,10 +753,10 @@ function kmlTextToGeoJson(text, sourceName) {
function filterKmlParcelFeatures(features) { function filterKmlParcelFeatures(features) {
const filtered = features.filter(feature => { const filtered = features.filter(feature => {
const properties = feature.properties || {}; if (isSheetOrOverlayFeature(feature)) {
if (properties["@geometry-type"] === "groundoverlay") {
return false; return false;
} }
const properties = feature.properties || {};
const name = String(properties.name || properties.Name || properties.LABEL || "").trim(); const name = String(properties.name || properties.Name || properties.LABEL || "").trim();
const identity = [name, properties.layer, properties.Layer, properties.type, properties.Tipo] const identity = [name, properties.layer, properties.Layer, properties.type, properties.Tipo]
.filter(Boolean) .filter(Boolean)
@@ -772,6 +771,28 @@ function filterKmlParcelFeatures(features) {
return removeLikelySheetOutlines(filtered); return removeLikelySheetOutlines(filtered);
} }
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;
}
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) { function splitKmlPolygonFeatures(features) {
const result = []; const result = [];
const addGeometry = (feature, geometry, partIndex) => { const addGeometry = (feature, geometry, partIndex) => {
@@ -878,6 +899,7 @@ function setIncludeKmlSheetLayer(enabled) {
} }
function setImportedSheetLayerVisible(enabled) { function setImportedSheetLayerVisible(enabled) {
migrateMisclassifiedImportedSheets();
lmeState.importedSheetsVisible = Boolean(enabled); lmeState.importedSheetsVisible = Boolean(enabled);
applyImportedSheetVisibility(); applyImportedSheetVisibility();
const count = lmeState.importedSheets?.toGeoJSON()?.features?.length || 0; const count = lmeState.importedSheets?.toGeoJSON()?.features?.length || 0;
@@ -886,6 +908,50 @@ function setImportedSheetLayerVisible(enabled) {
: "Layer del foglio importato nascosto; le particelle restano visibili."); : "Layer del foglio importato nascosto; le particelle restano visibili.");
} }
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(), {
style: { color: "#15803d", weight: 3, opacity: 0.85, fillOpacity: 0.04, dashArray: "9 7" },
pointToLayer: (feature, latlng) => L.circleMarker(latlng, {
radius: 6,
color: "#15803d",
fillOpacity: 0.25
}),
onEachFeature: bindStoredFeaturePopup
}).addTo(lmeState.importedSheets);
}
function applyImportedSheetVisibility() { function applyImportedSheetVisibility() {
if (!lmeState.map || !lmeState.importedSheets) { if (!lmeState.map || !lmeState.importedSheets) {
return; return;
@@ -950,11 +1016,7 @@ function addProjectMarker(name) {
setInfo(`POI aggiunto: ${label}`); setInfo(`POI aggiunto: ${label}`);
} }
function addQuickMeasureControl() { function configureDrawLabels() {
if (!lmeState.map || lmeState.quickMeasureControl) {
return;
}
L.drawLocal.draw.toolbar.buttons.polygon = "Misura area"; L.drawLocal.draw.toolbar.buttons.polygon = "Misura area";
L.drawLocal.draw.toolbar.buttons.polyline = "Misura distanza"; L.drawLocal.draw.toolbar.buttons.polyline = "Misura distanza";
L.drawLocal.draw.toolbar.buttons.circle = "Misura cerchio"; L.drawLocal.draw.toolbar.buttons.circle = "Misura cerchio";
@@ -969,32 +1031,6 @@ function addQuickMeasureControl() {
L.drawLocal.draw.handlers.polyline.tooltip.cont = "Tocca per aggiungere un tratto."; 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.polyline.tooltip.end = "Tocca l'ultimo punto per terminare.";
L.drawLocal.draw.handlers.circle.tooltip.start = "Tocca il centro e trascina per il raggio."; L.drawLocal.draw.handlers.circle.tooltip.start = "Tocca il centro e trascina per il raggio.";
const orangeArea = { color: "#f97316", weight: 4, fillColor: "#fb923c", fillOpacity: 0.2 };
lmeState.quickMeasureControl = new L.Control.Draw({
position: "topright",
edit: false,
draw: {
circle: { metric: true, feet: false, showRadius: true, shapeOptions: orangeArea },
circlemarker: false,
marker: false,
polygon: {
metric: true,
feet: false,
showArea: true,
allowIntersection: false,
shapeOptions: orangeArea
},
polyline: {
metric: true,
feet: false,
showLength: true,
shapeOptions: { color: "#f97316", weight: 4, opacity: 0.95 }
},
rectangle: false
}
});
lmeState.map.addControl(lmeState.quickMeasureControl);
} }
function bindDrawingEvents() { function bindDrawingEvents() {
@@ -1036,21 +1072,34 @@ function enableDrawTools() {
return; return;
} }
configureDrawLabels();
const orangeArea = { color: "#f97316", weight: 4, fillColor: "#fb923c", fillOpacity: 0.2 };
lmeState.drawControl = new L.Control.Draw({ lmeState.drawControl = new L.Control.Draw({
position: "topright", position: "topright",
edit: { featureGroup: lmeState.drawings }, edit: { featureGroup: lmeState.drawings },
draw: { draw: {
circle: false, circle: { metric: true, feet: false, showRadius: true, shapeOptions: orangeArea },
circlemarker: false, circlemarker: false,
marker: true, marker: true,
polygon: false, polygon: {
polyline: false, metric: true,
rectangle: { metric: true, shapeOptions: { color: "#f97316", weight: 4, fillOpacity: 0.2 } } 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); lmeState.map.addControl(lmeState.drawControl);
bindDrawingEvents(); bindDrawingEvents();
setInfo("Barra completa attiva: rettangolo, POI, modifica e cancellazione."); setInfo("Barra strumenti attiva: misure, disegni, POI, modifica e cancellazione.");
} }
function startMeasurementDrawing(mode) { function startMeasurementDrawing(mode) {
@@ -1374,10 +1423,89 @@ function formatNumber(value, digits) {
}).format(value); }).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) { function createProjectSnapshot(includeCadastralParcels) {
const center = lmeState.map.getCenter(); const center = lmeState.map.getCenter();
return JSON.stringify({ return JSON.stringify({
schemaVersion: 2, schemaVersion: 3,
view: { view: {
latitude: center.lat, latitude: center.lat,
longitude: center.lng, longitude: center.lng,
@@ -1387,6 +1515,7 @@ function createProjectSnapshot(includeCadastralParcels) {
imported: lmeState.imported.toGeoJSON(), imported: lmeState.imported.toGeoJSON(),
importedSheets: lmeState.importedSheets.toGeoJSON(), importedSheets: lmeState.importedSheets.toGeoJSON(),
importedSheetsVisible: lmeState.importedSheetsVisible, importedSheetsVisible: lmeState.importedSheetsVisible,
displayOptions: captureDisplayOptions(),
selectedParcels: includeCadastralParcels selectedParcels: includeCadastralParcels
? lmeState.selectedParcelsLayer.toGeoJSON() ? lmeState.selectedParcelsLayer.toGeoJSON()
: { type: "FeatureCollection", features: [] }, : { type: "FeatureCollection", features: [] },
@@ -1441,26 +1570,14 @@ function loadProjectSnapshot(raw, projectName) {
const importedParts = partitionStoredImportedFeatures( const importedParts = partitionStoredImportedFeatures(
data.imported || emptyFeatureCollection(), data.imported || emptyFeatureCollection(),
data.importedSheets || emptyFeatureCollection()); data.importedSheets || emptyFeatureCollection());
L.geoJSON(importedParts.parcels, { addImportedFeatures(importedParts.parcels);
style: { color: "#22c55e", weight: 3, opacity: 0.95, fillOpacity: 0.18 }, addImportedSheetFeatures(importedParts.sheets);
pointToLayer: (feature, latlng) => L.circleMarker(latlng, { const projectDisplayOptions = data.schemaVersion >= 3 && data.displayOptions
radius: 7, ? data.displayOptions
color: "#22c55e", : null;
fillColor: "#ffffff", lmeState.importedSheetsVisible = projectDisplayOptions
fillOpacity: 0.9 ? Boolean(projectDisplayOptions.importedSheetsVisible)
}), : data.schemaVersion >= 2 && Boolean(data.importedSheetsVisible);
onEachFeature: bindStoredFeaturePopup
}).addTo(lmeState.imported);
L.geoJSON(importedParts.sheets, {
style: { color: "#15803d", weight: 3, opacity: 0.85, fillOpacity: 0.04, dashArray: "9 7" },
pointToLayer: (feature, latlng) => L.circleMarker(latlng, {
radius: 6,
color: "#15803d",
fillOpacity: 0.25
}),
onEachFeature: bindStoredFeaturePopup
}).addTo(lmeState.importedSheets);
lmeState.importedSheetsVisible = data.schemaVersion >= 2 && Boolean(data.importedSheetsVisible);
applyImportedSheetVisibility(); applyImportedSheetVisibility();
L.geoJSON(data.selectedParcels || emptyFeatureCollection(), { L.geoJSON(data.selectedParcels || emptyFeatureCollection(), {
style: { color: "#ef4444", weight: 4, opacity: 1, fillColor: "#fbbf24", fillOpacity: 0.26 }, style: { color: "#ef4444", weight: 4, opacity: 1, fillColor: "#fbbf24", fillOpacity: 0.26 },
@@ -1477,6 +1594,9 @@ function loadProjectSnapshot(raw, projectName) {
lmeState.gpsTrailPoints = Array.isArray(data.trail) ? data.trail : []; lmeState.gpsTrailPoints = Array.isArray(data.trail) ? data.trail : [];
lmeState.gpsTrail.setLatLngs(lmeState.gpsTrailPoints); lmeState.gpsTrail.setLatLngs(lmeState.gpsTrailPoints);
if (projectDisplayOptions) {
applyProjectDisplayOptions(projectDisplayOptions);
}
refreshImportedMeasurements(); refreshImportedMeasurements();
refreshDrawingMeasurements(); refreshDrawingMeasurements();
@@ -1507,19 +1627,70 @@ function loadProjectSnapshot(raw, projectName) {
? ` ${importedParts.sheets.features.length} elementi del foglio sono nascosti.` ? ` ${importedParts.sheets.features.length} elementi del foglio sono nascosti.`
: ""; : "";
setInfo(`Progetto caricato: ${projectName || "senza nome"}.${hiddenSheets}`); setInfo(`Progetto caricato: ${projectName || "senza nome"}.${hiddenSheets}`);
return lmeState.importedSheetsVisible; return captureDisplayOptions();
} catch (error) { } catch (error) {
setInfo(`Progetto non leggibile: ${error.message}`); setInfo(`Progetto non leggibile: ${error.message}`);
throw error; 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) { function partitionStoredImportedFeatures(imported, storedSheets) {
const parcelFeatures = []; const parcelFeatures = [];
const sheetFeatures = [...(storedSheets?.features || [])]; const sheetFeatures = [...(storedSheets?.features || [])];
const sourceGroups = new Map(); const sourceGroups = new Map();
(imported?.features || []).forEach(feature => { (imported?.features || []).forEach(feature => {
if (isSheetOrOverlayFeature(feature)) {
sheetFeatures.push(feature);
return;
}
const source = String(feature?.properties?._lmeSource || ""); const source = String(feature?.properties?._lmeSource || "");
if (!/\.(kml|kmz)$/i.test(source)) { if (!/\.(kml|kmz)$/i.test(source)) {
parcelFeatures.push(feature); parcelFeatures.push(feature);
@@ -1748,7 +1919,11 @@ function htmlToText(value) {
} }
function setCadastreOpacity(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) { if (lmeState.cadastre) {
lmeState.cadastre.setOpacity(lmeState.cadastreOpacity); lmeState.cadastre.setOpacity(lmeState.cadastreOpacity);
} }