Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8b8f21d8d | ||
|
|
ff2d4bccb6 |
No files matched your search
+256
-14
@@ -5,6 +5,7 @@
|
||||
@inject OfficialCadastreService OfficialCadastreService
|
||||
@inject LocationSearchService LocationSearchService
|
||||
@inject AzureMapsService AzureMapsService
|
||||
@inject ProjectStorageService ProjectStorageService
|
||||
@implements IAsyncDisposable
|
||||
|
||||
<PageTitle>LME Mappe Catastali</PageTitle>
|
||||
@@ -156,24 +157,66 @@
|
||||
<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>
|
||||
</label>
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<h2>Progetti e POI</h2>
|
||||
<h2>Archivio progetti</h2>
|
||||
<label>
|
||||
Nome
|
||||
<input @bind="ProjectName" @bind:event="oninput" placeholder="Nome progetto o POI" />
|
||||
Nome progetto
|
||||
<input @bind="NewProjectName" @bind:event="oninput" placeholder="Es. Rilievo San Nicola" maxlength="80" />
|
||||
</label>
|
||||
<label class="toggle-line project-save-option">
|
||||
<input type="checkbox" @bind="IncludeCadastralParcels" />
|
||||
<span>Includi le particelle catastali rosse</span>
|
||||
</label>
|
||||
<button class="primary-command" @onclick="SaveProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(NewProjectName))">Salva progetto</button>
|
||||
|
||||
<label>
|
||||
Progetto salvato
|
||||
<select value="@SelectedProjectId" @onchange="SelectProject" disabled="@(Projects.Count == 0 || ProjectBusy)">
|
||||
<option value="">Seleziona un progetto</option>
|
||||
@foreach (var project in Projects)
|
||||
{
|
||||
<option value="@project.Id">@project.Name - @project.UpdatedAt.ToLocalTime().ToString("dd/MM/yyyy HH:mm")</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<div class="button-row">
|
||||
<button @onclick="LoadProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Carica</button>
|
||||
<button class="danger-command" @onclick="DeleteProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Elimina</button>
|
||||
</div>
|
||||
<div class="project-archive-state">@ProjectArchiveMessage</div>
|
||||
|
||||
<h2>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>
|
||||
<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 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="secondary-command" aria-pressed="@DrawToolsVisible" @onclick="ToggleDrawTools">
|
||||
@(DrawToolsVisible ? "Nascondi strumenti di disegno" : "Mostra strumenti di disegno")
|
||||
</button>
|
||||
<div class="button-row">
|
||||
<button @onclick="SaveWorkspace">Salva</button>
|
||||
<button @onclick="LoadWorkspace">Carica</button>
|
||||
</div>
|
||||
<button class="danger-command" @onclick="ClearDrawings">Elimina disegni e POI</button>
|
||||
</section>
|
||||
}
|
||||
@@ -268,7 +311,10 @@
|
||||
@code {
|
||||
private string ActiveTab { get; set; } = "map";
|
||||
private string SearchText { get; set; } = string.Empty;
|
||||
private string ProjectName { get; set; } = string.Empty;
|
||||
private string NewProjectName { get; set; } = string.Empty;
|
||||
private string PoiName { get; set; } = string.Empty;
|
||||
private string SelectedProjectId { get; set; } = string.Empty;
|
||||
private string ProjectArchiveMessage { get; set; } = "Nessun progetto salvato.";
|
||||
private string Status { get; set; } = "online";
|
||||
private string SelectedBaseLayer { get; set; } = "satellite";
|
||||
private string GoogleMapsApiKey { get; set; } = string.Empty;
|
||||
@@ -284,6 +330,11 @@
|
||||
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 ShowImportedMeasurements { get; set; }
|
||||
private bool ShowDrawingMeasurements { get; set; } = true;
|
||||
private bool ProjectBusy { get; set; }
|
||||
private CancellationTokenSource? CatalogCancellation { get; set; }
|
||||
private CancellationTokenSource? GpsLookupCancellation { get; set; }
|
||||
private long LastGpsLookupAt;
|
||||
@@ -293,6 +344,7 @@
|
||||
private IReadOnlyList<MunicipalityOption> Municipalities { get; set; } = [];
|
||||
private IReadOnlyList<string> Sheets { get; set; } = [];
|
||||
private IReadOnlyList<ParcelOption> Parcels { get; set; } = [];
|
||||
private IReadOnlyList<MapProjectSummary> Projects { get; set; } = [];
|
||||
|
||||
private MunicipalityOption? SelectedMunicipality =>
|
||||
Municipalities.FirstOrDefault(item => item.Code == SelectedMunicipalityCode);
|
||||
@@ -354,6 +406,8 @@
|
||||
{
|
||||
CatalogMessage = $"Catalogo Comuni non disponibile: {error.Message}";
|
||||
}
|
||||
|
||||
await RefreshProjectsAsync();
|
||||
}
|
||||
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
@@ -361,6 +415,32 @@
|
||||
if (firstRender)
|
||||
{
|
||||
await JS.InvokeVoidAsync("lmeMap.init");
|
||||
await MigrateLegacyProjectAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task MigrateLegacyProjectAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var legacySnapshot = await JS.InvokeAsync<string?>("lmeMap.getLegacyProjectSnapshot");
|
||||
if (string.IsNullOrWhiteSpace(legacySnapshot))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var migrated = await ProjectStorageService.SaveAsync(
|
||||
"Progetto precedente",
|
||||
legacySnapshot,
|
||||
false);
|
||||
await JS.InvokeVoidAsync("lmeMap.clearLegacyProjectSnapshot");
|
||||
await RefreshProjectsAsync();
|
||||
SelectedProjectId = migrated.Id;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// The legacy value remains available and migration can be retried at the next start.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -371,6 +451,10 @@
|
||||
{
|
||||
LayerPanelOpen = false;
|
||||
}
|
||||
if (tab == "projects")
|
||||
{
|
||||
await RefreshProjectsAsync();
|
||||
}
|
||||
await Task.Delay(30);
|
||||
await JS.InvokeVoidAsync("lmeMap.resize");
|
||||
}
|
||||
@@ -665,7 +749,37 @@
|
||||
|
||||
private Task FitImportedLayers() => JS.InvokeVoidAsync("lmeMap.fitImported").AsTask();
|
||||
private Task ClearImportedLayers() => JS.InvokeVoidAsync("lmeMap.clearImported").AsTask();
|
||||
private Task AddProjectMarker() => JS.InvokeVoidAsync("lmeMap.addProjectMarker", ProjectName).AsTask();
|
||||
private Task AddProjectMarker() => JS.InvokeVoidAsync("lmeMap.addProjectMarker", PoiName).AsTask();
|
||||
|
||||
private async Task ToggleImportParcelsOnly(ChangeEventArgs args)
|
||||
{
|
||||
ImportParcelsOnly = (bool?)args.Value == true;
|
||||
await JS.InvokeVoidAsync("lmeMap.setImportParcelOnly", ImportParcelsOnly);
|
||||
}
|
||||
|
||||
private async Task ToggleImportedMeasurements(ChangeEventArgs args)
|
||||
{
|
||||
ShowImportedMeasurements = (bool?)args.Value == true;
|
||||
await JS.InvokeVoidAsync("lmeMap.setImportedMeasurementsVisible", ShowImportedMeasurements);
|
||||
}
|
||||
|
||||
private async Task ToggleDrawingMeasurements(ChangeEventArgs args)
|
||||
{
|
||||
ShowDrawingMeasurements = (bool?)args.Value == true;
|
||||
await JS.InvokeVoidAsync("lmeMap.setDrawingMeasurementsVisible", ShowDrawingMeasurements);
|
||||
}
|
||||
|
||||
private async Task StartMeasurementDrawing(string mode)
|
||||
{
|
||||
DrawToolsVisible = false;
|
||||
await JS.InvokeVoidAsync("lmeMap.setDrawToolsVisible", false);
|
||||
ActiveTab = "map";
|
||||
LayerPanelOpen = false;
|
||||
await Task.Delay(30);
|
||||
await JS.InvokeVoidAsync("lmeMap.resize");
|
||||
await JS.InvokeVoidAsync("lmeMap.startMeasurementDrawing", mode);
|
||||
}
|
||||
|
||||
private async Task ToggleDrawTools()
|
||||
{
|
||||
DrawToolsVisible = !DrawToolsVisible;
|
||||
@@ -678,8 +792,136 @@
|
||||
}
|
||||
|
||||
private Task ClearDrawings() => JS.InvokeVoidAsync("lmeMap.clearDrawings").AsTask();
|
||||
private Task SaveWorkspace() => JS.InvokeVoidAsync("lmeMap.saveWorkspace").AsTask();
|
||||
private Task LoadWorkspace() => JS.InvokeVoidAsync("lmeMap.loadWorkspace").AsTask();
|
||||
|
||||
private async Task RefreshProjectsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
Projects = await ProjectStorageService.GetProjectsAsync();
|
||||
if (Projects.All(project => project.Id != SelectedProjectId))
|
||||
{
|
||||
SelectedProjectId = string.Empty;
|
||||
}
|
||||
ProjectArchiveMessage = Projects.Count == 0
|
||||
? "Nessun progetto salvato."
|
||||
: $"{Projects.Count} {(Projects.Count == 1 ? "progetto salvato" : "progetti salvati")} nell'archivio interno.";
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
ProjectArchiveMessage = $"Archivio non disponibile: {error.GetBaseException().Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private Task SelectProject(ChangeEventArgs args)
|
||||
{
|
||||
SelectedProjectId = args.Value?.ToString() ?? string.Empty;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task SaveProject()
|
||||
{
|
||||
var name = NewProjectName.Trim();
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
{
|
||||
await JS.InvokeVoidAsync("lmeMap.showInfo", "Inserisci il nome del progetto.");
|
||||
return;
|
||||
}
|
||||
|
||||
var existing = Projects.FirstOrDefault(project =>
|
||||
string.Equals(project.Name, name, StringComparison.CurrentCultureIgnoreCase));
|
||||
if (existing is not null
|
||||
&& !await JS.InvokeAsync<bool>("confirm", $"Il progetto '{existing.Name}' esiste gia. Sovrascriverlo?"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ProjectBusy = true;
|
||||
try
|
||||
{
|
||||
var snapshot = await JS.InvokeAsync<string>("lmeMap.createProjectSnapshot", IncludeCadastralParcels);
|
||||
var saved = await ProjectStorageService.SaveAsync(
|
||||
name,
|
||||
snapshot,
|
||||
IncludeCadastralParcels,
|
||||
existing?.Id);
|
||||
await RefreshProjectsAsync();
|
||||
SelectedProjectId = saved.Id;
|
||||
NewProjectName = saved.Name;
|
||||
await JS.InvokeVoidAsync(
|
||||
"lmeMap.showInfo",
|
||||
IncludeCadastralParcels
|
||||
? $"Progetto salvato: {saved.Name}, incluse le particelle rosse."
|
||||
: $"Progetto salvato: {saved.Name}, senza particelle rosse.");
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Progetto non salvato: {error.GetBaseException().Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ProjectBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LoadProject()
|
||||
{
|
||||
var project = Projects.FirstOrDefault(item => item.Id == SelectedProjectId);
|
||||
if (project is null)
|
||||
{
|
||||
await JS.InvokeVoidAsync("lmeMap.showInfo", "Seleziona il progetto da caricare.");
|
||||
return;
|
||||
}
|
||||
|
||||
ProjectBusy = true;
|
||||
try
|
||||
{
|
||||
var snapshot = await ProjectStorageService.LoadAsync(project.Id);
|
||||
await JS.InvokeVoidAsync("lmeMap.loadProjectSnapshot", snapshot, project.Name);
|
||||
NewProjectName = project.Name;
|
||||
IncludeCadastralParcels = project.IncludesCadastralParcels;
|
||||
ActiveTab = "map";
|
||||
await Task.Delay(30);
|
||||
await JS.InvokeVoidAsync("lmeMap.resize");
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Progetto non caricato: {error.GetBaseException().Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ProjectBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DeleteProject()
|
||||
{
|
||||
var project = Projects.FirstOrDefault(item => item.Id == SelectedProjectId);
|
||||
if (project is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (!await JS.InvokeAsync<bool>("confirm", $"Eliminare definitivamente il progetto '{project.Name}'?"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ProjectBusy = true;
|
||||
try
|
||||
{
|
||||
await ProjectStorageService.DeleteAsync(project.Id);
|
||||
SelectedProjectId = string.Empty;
|
||||
await RefreshProjectsAsync();
|
||||
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Progetto eliminato: {project.Name}.");
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Progetto non eliminato: {error.GetBaseException().Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ProjectBusy = false;
|
||||
}
|
||||
}
|
||||
private Task CenterOnGps() => JS.InvokeVoidAsync("lmeMap.centerOnGps").AsTask();
|
||||
private async Task ToggleTrail(ChangeEventArgs args)
|
||||
{
|
||||
|
||||
@@ -28,8 +28,8 @@
|
||||
<ApplicationId>com.companyname.lmemappecatastaliapp</ApplicationId>
|
||||
|
||||
<!-- Versions -->
|
||||
<ApplicationDisplayVersion>0.2.6</ApplicationDisplayVersion>
|
||||
<ApplicationVersion>10</ApplicationVersion>
|
||||
<ApplicationDisplayVersion>0.2.8</ApplicationDisplayVersion>
|
||||
<ApplicationVersion>12</ApplicationVersion>
|
||||
|
||||
<!-- To develop, package, and publish an app to the Microsoft Store, see: https://aka.ms/MauiTemplateUnpackaged -->
|
||||
<WindowsPackageType>None</WindowsPackageType>
|
||||
|
||||
@@ -21,6 +21,7 @@ public static class MauiProgram
|
||||
builder.Services.AddSingleton<OfficialCadastreService>();
|
||||
builder.Services.AddSingleton<LocationSearchService>();
|
||||
builder.Services.AddSingleton<AzureMapsService>();
|
||||
builder.Services.AddSingleton<ProjectStorageService>();
|
||||
|
||||
#if DEBUG
|
||||
builder.Services.AddBlazorWebViewDeveloperTools();
|
||||
|
||||
@@ -9,10 +9,15 @@ App .NET MAUI Blazor Hybrid per Android, iOS, Mac Catalyst e Windows, pensata pe
|
||||
- Trasparenza configurabile del layer catastale.
|
||||
- Interrogazione WMS con click/tap sulla mappa.
|
||||
- Import di file KML, KMZ, GeoJSON e JSON.
|
||||
- Import GeoJSON compatibile con BOM, geometrie singole, array, FeatureCollection e coordinate Web Mercator EPSG:3857.
|
||||
- Filtro KML/KMZ `solo particelle` attivo per impostazione predefinita, con esclusione di GroundOverlay e perimetri del foglio.
|
||||
- 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.
|
||||
- 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.
|
||||
- POI/progetti salvabili in locale con `localStorage`.
|
||||
- Archivio multiprogetto nella cartella privata dell'app, con nome, selezione da elenco, sovrascrittura ed eliminazione.
|
||||
- Ogni progetto salva file GIS, POI, disegni, traccia e inquadratura; l'inclusione delle particelle catastali rosse e' opzionale.
|
||||
- GPS nativo MAUI ad alta precisione con permessi Android/iOS.
|
||||
- Marker posizione, cerchio accuratezza in metri, tracciamento percorso.
|
||||
- Controllo se la posizione GPS cade dentro un poligono importato o disegnato.
|
||||
|
||||
@@ -13,7 +13,7 @@ public sealed class AzureMapsService
|
||||
|
||||
public AzureMapsService()
|
||||
{
|
||||
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LMEMappeCatastali/0.2.6");
|
||||
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LMEMappeCatastali/0.2.8");
|
||||
_httpClient.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace LMEMappeCatastaliApp.Services;
|
||||
|
||||
public sealed class ProjectStorageService
|
||||
{
|
||||
private const string ProjectExtension = ".lmeproject.json";
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
private string ProjectsDirectory => Path.Combine(FileSystem.AppDataDirectory, "Projects");
|
||||
|
||||
public async Task<IReadOnlyList<MapProjectSummary>> GetProjectsAsync()
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
var files = await ReadProjectFilesAsync();
|
||||
return files
|
||||
.Select(item => item.Document.ToSummary())
|
||||
.OrderByDescending(item => item.UpdatedAt)
|
||||
.ThenBy(item => item.Name, StringComparer.CurrentCultureIgnoreCase)
|
||||
.ToArray();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<MapProjectSummary> SaveAsync(
|
||||
string name,
|
||||
string snapshotJson,
|
||||
bool includesCadastralParcels,
|
||||
string? projectId = null)
|
||||
{
|
||||
var normalizedName = NormalizeName(name);
|
||||
using var snapshotDocument = JsonDocument.Parse(snapshotJson);
|
||||
if (snapshotDocument.RootElement.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
throw new InvalidDataException("I dati della mappa non sono validi.");
|
||||
}
|
||||
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(ProjectsDirectory);
|
||||
var files = await ReadProjectFilesAsync();
|
||||
var existing = files.FirstOrDefault(item =>
|
||||
(!string.IsNullOrWhiteSpace(projectId) && item.Document.Id == projectId)
|
||||
|| string.Equals(item.Document.Name, normalizedName, StringComparison.CurrentCultureIgnoreCase));
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var id = existing?.Document.Id ?? Guid.NewGuid().ToString("N");
|
||||
var document = new MapProjectDocument
|
||||
{
|
||||
SchemaVersion = 1,
|
||||
Id = id,
|
||||
Name = normalizedName,
|
||||
CreatedAt = existing?.Document.CreatedAt ?? now,
|
||||
UpdatedAt = now,
|
||||
IncludesCadastralParcels = includesCadastralParcels,
|
||||
Map = snapshotDocument.RootElement.Clone()
|
||||
};
|
||||
|
||||
var path = existing?.Path ?? Path.Combine(ProjectsDirectory, BuildFileName(normalizedName, id));
|
||||
var temporaryPath = path + ".tmp";
|
||||
try
|
||||
{
|
||||
await File.WriteAllTextAsync(
|
||||
temporaryPath,
|
||||
JsonSerializer.Serialize(document, _jsonOptions),
|
||||
new UTF8Encoding(false));
|
||||
File.Move(temporaryPath, path, true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(temporaryPath))
|
||||
{
|
||||
File.Delete(temporaryPath);
|
||||
}
|
||||
}
|
||||
|
||||
return document.ToSummary();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> LoadAsync(string projectId)
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
var project = (await ReadProjectFilesAsync())
|
||||
.FirstOrDefault(item => item.Document.Id == projectId)
|
||||
?? throw new FileNotFoundException("Il progetto selezionato non esiste piu'.");
|
||||
return project.Document.Map.GetRawText();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(string projectId)
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
var project = (await ReadProjectFilesAsync())
|
||||
.FirstOrDefault(item => item.Document.Id == projectId)
|
||||
?? throw new FileNotFoundException("Il progetto selezionato non esiste piu'.");
|
||||
File.Delete(project.Path);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<ProjectFileEntry>> ReadProjectFilesAsync()
|
||||
{
|
||||
Directory.CreateDirectory(ProjectsDirectory);
|
||||
var projects = new List<ProjectFileEntry>();
|
||||
foreach (var path in Directory.EnumerateFiles(ProjectsDirectory, $"*{ProjectExtension}"))
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var stream = File.OpenRead(path);
|
||||
var document = await JsonSerializer.DeserializeAsync<MapProjectDocument>(stream, _jsonOptions);
|
||||
if (document is not null
|
||||
&& !string.IsNullOrWhiteSpace(document.Id)
|
||||
&& !string.IsNullOrWhiteSpace(document.Name)
|
||||
&& document.Map.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
projects.Add(new ProjectFileEntry(path, document));
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// A damaged project is ignored so the remaining archive stays usable.
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return projects;
|
||||
}
|
||||
|
||||
private static string NormalizeName(string name)
|
||||
{
|
||||
var normalized = string.Join(' ', (name ?? string.Empty).Split(
|
||||
[' ', '\t', '\r', '\n'],
|
||||
StringSplitOptions.RemoveEmptyEntries));
|
||||
if (string.IsNullOrWhiteSpace(normalized))
|
||||
{
|
||||
throw new ArgumentException("Inserisci il nome del progetto.");
|
||||
}
|
||||
|
||||
return normalized.Length <= 80 ? normalized : normalized[..80];
|
||||
}
|
||||
|
||||
private static string BuildFileName(string name, string id)
|
||||
{
|
||||
var invalid = Path.GetInvalidFileNameChars().ToHashSet();
|
||||
var safeName = new string(name
|
||||
.Select(character => invalid.Contains(character) ? '-' : character)
|
||||
.ToArray())
|
||||
.Trim(' ', '.');
|
||||
safeName = string.IsNullOrWhiteSpace(safeName) ? "Progetto" : safeName;
|
||||
return $"{safeName}--{id[..8]}{ProjectExtension}";
|
||||
}
|
||||
|
||||
private sealed record ProjectFileEntry(string Path, MapProjectDocument Document);
|
||||
|
||||
private sealed class MapProjectDocument
|
||||
{
|
||||
public int SchemaVersion { get; init; }
|
||||
public string Id { get; init; } = string.Empty;
|
||||
public string Name { get; init; } = string.Empty;
|
||||
public DateTimeOffset CreatedAt { get; init; }
|
||||
public DateTimeOffset UpdatedAt { get; init; }
|
||||
public bool IncludesCadastralParcels { get; init; }
|
||||
public JsonElement Map { get; init; }
|
||||
|
||||
public MapProjectSummary ToSummary() => new(Id, Name, UpdatedAt, IncludesCadastralParcels);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record MapProjectSummary(
|
||||
string Id,
|
||||
string Name,
|
||||
DateTimeOffset UpdatedAt,
|
||||
bool IncludesCadastralParcels);
|
||||
@@ -459,6 +459,69 @@ label {
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.project-save-option {
|
||||
padding: 10px 11px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.project-archive-state {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.measurement-mode-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.measurement-mode-grid button {
|
||||
min-width: 0;
|
||||
padding: 0 8px;
|
||||
}
|
||||
|
||||
.lme-measure-label {
|
||||
width: 0 !important;
|
||||
height: 0 !important;
|
||||
border: 0 !important;
|
||||
background: transparent !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
.lme-measure-label span {
|
||||
position: absolute;
|
||||
transform: translate(-50%, -50%);
|
||||
border: 1px solid rgba(23, 33, 43, 0.35);
|
||||
border-radius: 4px;
|
||||
padding: 2px 5px;
|
||||
background: rgba(255, 255, 255, 0.92);
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.24);
|
||||
color: #17212b;
|
||||
font-size: 10px;
|
||||
font-weight: 800;
|
||||
line-height: 1.25;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.lme-measure-label.imported span {
|
||||
border-color: #15806a;
|
||||
color: #0c5749;
|
||||
}
|
||||
|
||||
.lme-measure-label.drawing span {
|
||||
border-color: #d35d0b;
|
||||
color: #7c2d12;
|
||||
}
|
||||
|
||||
.lme-measure-label.side span {
|
||||
padding: 1px 4px;
|
||||
font-size: 9px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.map-info {
|
||||
position: absolute;
|
||||
left: 12px;
|
||||
|
||||
+806
-38
@@ -7,9 +7,16 @@ const lmeState = {
|
||||
cadastreLayers: ["CP.CadastralParcel", "codice_plla", "CP.CadastralZoning", "fabbricati"],
|
||||
cadastreOpacity: 0.75,
|
||||
imported: null,
|
||||
importedMeasurements: null,
|
||||
drawings: null,
|
||||
drawingMeasurements: null,
|
||||
drawControl: null,
|
||||
activeDrawHandler: null,
|
||||
drawEventsBound: false,
|
||||
importParcelOnly: true,
|
||||
showImportedMeasurements: false,
|
||||
showDrawingMeasurements: true,
|
||||
measurementRefreshTimer: null,
|
||||
gpsMarker: null,
|
||||
gpsAccuracy: null,
|
||||
gpsTrail: null,
|
||||
@@ -40,11 +47,17 @@ window.lmeMap = {
|
||||
clearMapElements,
|
||||
fitImported,
|
||||
clearImported,
|
||||
setImportParcelOnly,
|
||||
setImportedMeasurementsVisible,
|
||||
setDrawingMeasurementsVisible,
|
||||
addProjectMarker,
|
||||
startMeasurementDrawing,
|
||||
setDrawToolsVisible,
|
||||
clearDrawings,
|
||||
saveWorkspace,
|
||||
loadWorkspace,
|
||||
createProjectSnapshot,
|
||||
loadProjectSnapshot,
|
||||
getLegacyProjectSnapshot,
|
||||
clearLegacyProjectSnapshot,
|
||||
setBaseLayer,
|
||||
configureGoogleMaps,
|
||||
configureAzureMaps,
|
||||
@@ -112,6 +125,8 @@ function init() {
|
||||
lmeState.currentBase = lmeState.baseLayers.satellite.addTo(lmeState.map);
|
||||
lmeState.imported = L.featureGroup().addTo(lmeState.map);
|
||||
lmeState.drawings = L.featureGroup().addTo(lmeState.map);
|
||||
lmeState.importedMeasurements = L.layerGroup().addTo(lmeState.map);
|
||||
lmeState.drawingMeasurements = L.layerGroup().addTo(lmeState.map);
|
||||
lmeState.selectedParcelsLayer = L.featureGroup().addTo(lmeState.map);
|
||||
lmeState.gpsParcelLayer = L.featureGroup().addTo(lmeState.map);
|
||||
lmeState.gpsTrail = L.polyline([], { color: "#f97316", weight: 4, opacity: 0.85 }).addTo(lmeState.map);
|
||||
@@ -131,7 +146,10 @@ function init() {
|
||||
L.popup().setLatLng(event.latlng).setContent(info).openOn(lmeState.map);
|
||||
}
|
||||
});
|
||||
lmeState.map.on("moveend", () => void updateAzureAttribution());
|
||||
lmeState.map.on("moveend", () => {
|
||||
void updateAzureAttribution();
|
||||
scheduleMeasurementRefresh();
|
||||
});
|
||||
|
||||
document.getElementById("closeWmsPreview")?.addEventListener("click", closeCadastrePreview);
|
||||
document.getElementById("wmsPreview")?.addEventListener("click", event => {
|
||||
@@ -197,7 +215,7 @@ function displayOfficialParcel(xmlText, latitude, longitude, parcel, label, shou
|
||||
}
|
||||
|
||||
const existingLayer = normalizedParcel
|
||||
? targetGroup.getLayers().find(item => item.lmeParcelReference === ref)
|
||||
? findParcelLayerByReference(targetGroup, ref)
|
||||
: null;
|
||||
if (existingLayer) {
|
||||
if (shouldFit) {
|
||||
@@ -235,6 +253,23 @@ function normalizeParcel(parcel) {
|
||||
return String(parcel || "").trim().toUpperCase();
|
||||
}
|
||||
|
||||
function findParcelLayerByReference(group, reference) {
|
||||
let match = null;
|
||||
group.eachLayer(layer => {
|
||||
if (match) {
|
||||
return;
|
||||
}
|
||||
if (layer.lmeParcelReference === reference) {
|
||||
match = layer;
|
||||
return;
|
||||
}
|
||||
if (typeof layer.eachLayer === "function") {
|
||||
match = findParcelLayerByReference(layer, reference);
|
||||
}
|
||||
});
|
||||
return match;
|
||||
}
|
||||
|
||||
function resize() {
|
||||
if (!lmeState.map) {
|
||||
return;
|
||||
@@ -398,7 +433,8 @@ function bindFileImport() {
|
||||
}
|
||||
|
||||
try {
|
||||
const geojson = await readGisFile(file);
|
||||
const result = await readGisFile(file);
|
||||
const geojson = result.geojson;
|
||||
const layer = L.geoJSON(geojson, {
|
||||
style: { color: "#22c55e", weight: 3, opacity: 0.95, fillOpacity: 0.18 },
|
||||
pointToLayer: (feature, latlng) => L.circleMarker(latlng, { radius: 7, color: "#22c55e", fillColor: "#ffffff", fillOpacity: 0.9 }),
|
||||
@@ -408,10 +444,18 @@ function bindFileImport() {
|
||||
}
|
||||
}).addTo(lmeState.imported);
|
||||
fitLayer(layer);
|
||||
setInfo(`Caricato ${file.name}`);
|
||||
refreshImportedMeasurements();
|
||||
const featureCount = geojson.features.length;
|
||||
const ignored = result.ignoredCount
|
||||
? `; esclusi ${result.ignoredCount} elementi non particella`
|
||||
: "";
|
||||
const reprojected = result.reprojected ? "; coordinate Web Mercator convertite" : "";
|
||||
setInfo(`Caricato ${file.name}: ${featureCount} elementi${ignored}${reprojected}.`);
|
||||
updateGpsInsideState();
|
||||
} catch (error) {
|
||||
setInfo(`File non leggibile: ${error.message}`);
|
||||
} finally {
|
||||
event.target.value = "";
|
||||
}
|
||||
});
|
||||
lmeState.fileImportBound = true;
|
||||
@@ -421,28 +465,336 @@ async function readGisFile(file) {
|
||||
const lowerName = file.name.toLowerCase();
|
||||
|
||||
if (lowerName.endsWith(".geojson") || lowerName.endsWith(".json")) {
|
||||
return JSON.parse(await file.text());
|
||||
const text = (await readFileText(file)).replace(/^\uFEFF/, "").trim();
|
||||
if (!text) {
|
||||
throw new Error("GeoJSON vuoto");
|
||||
}
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
if (typeof parsed === "string") {
|
||||
parsed = JSON.parse(parsed);
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(`GeoJSON non valido: ${error.message}`);
|
||||
}
|
||||
return normalizeGeoJson(parsed, file.name);
|
||||
}
|
||||
|
||||
if (lowerName.endsWith(".kml")) {
|
||||
return kmlTextToGeoJson(await file.text());
|
||||
return normalizeKmlFiles([{ name: file.name, text: await readFileText(file) }]);
|
||||
}
|
||||
|
||||
if (lowerName.endsWith(".kmz")) {
|
||||
const zip = await JSZip.loadAsync(await file.arrayBuffer());
|
||||
const kmlName = Object.keys(zip.files).find(name => name.toLowerCase().endsWith(".kml"));
|
||||
if (!kmlName) {
|
||||
const kmlEntries = Object.values(zip.files).filter(entry =>
|
||||
!entry.dir
|
||||
&& !entry.name.startsWith("__MACOSX/")
|
||||
&& entry.name.toLowerCase().endsWith(".kml"));
|
||||
if (!kmlEntries.length) {
|
||||
throw new Error("KMZ senza file KML interno");
|
||||
}
|
||||
return kmlTextToGeoJson(await zip.files[kmlName].async("text"));
|
||||
const files = await Promise.all(kmlEntries.map(async entry => ({
|
||||
name: entry.name,
|
||||
text: await entry.async("text")
|
||||
})));
|
||||
return normalizeKmlFiles(files);
|
||||
}
|
||||
|
||||
throw new Error("Formato supportato: KML, KMZ, GeoJSON");
|
||||
}
|
||||
|
||||
function kmlTextToGeoJson(text) {
|
||||
function readFileText(file) {
|
||||
if (typeof file.text === "function") {
|
||||
return file.text();
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result || ""));
|
||||
reader.onerror = () => reject(new Error("lettura del file non riuscita"));
|
||||
reader.readAsText(file);
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeGeoJson(value, fileName) {
|
||||
let root;
|
||||
if (Array.isArray(value)) {
|
||||
root = {
|
||||
type: "FeatureCollection",
|
||||
features: value.map(item => item?.type === "Feature"
|
||||
? item
|
||||
: { type: "Feature", properties: {}, geometry: item })
|
||||
};
|
||||
} else if (value?.type === "FeatureCollection") {
|
||||
root = value;
|
||||
} else if (value?.type === "Feature") {
|
||||
root = { type: "FeatureCollection", features: [value], crs: value.crs };
|
||||
} else if (isGeoJsonGeometry(value)) {
|
||||
root = {
|
||||
type: "FeatureCollection",
|
||||
features: [{ type: "Feature", properties: {}, geometry: value }],
|
||||
crs: value.crs
|
||||
};
|
||||
} else {
|
||||
throw new Error("il contenuto non e' un Feature, una geometria o una FeatureCollection");
|
||||
}
|
||||
|
||||
root.features = (root.features || []).filter(feature => feature?.type === "Feature" && feature.geometry);
|
||||
if (!root.features.length) {
|
||||
throw new Error("nessuna geometria presente nel GeoJSON");
|
||||
}
|
||||
root.features.forEach(feature => {
|
||||
feature.properties = feature.properties && typeof feature.properties === "object"
|
||||
? feature.properties
|
||||
: {};
|
||||
feature.properties._lmeSource = feature.properties._lmeSource || fileName;
|
||||
});
|
||||
|
||||
const crsText = root.crs ? JSON.stringify(root.crs).toUpperCase() : "";
|
||||
const coordinates = collectGeoJsonCoordinates(root);
|
||||
const hasProjectedCoordinates = coordinates.some(point => Math.abs(point[0]) > 180 || Math.abs(point[1]) > 90);
|
||||
const webMercator = /EPSG[^0-9]*(3857|900913)/.test(crsText)
|
||||
|| (!crsText && hasProjectedCoordinates && coordinates.every(point =>
|
||||
Math.abs(point[0]) <= 20037508.35 && Math.abs(point[1]) <= 20048966.1));
|
||||
|
||||
if (webMercator) {
|
||||
root.features.forEach(feature => {
|
||||
feature.geometry = transformGeoJsonGeometry(feature.geometry, webMercatorToWgs84);
|
||||
});
|
||||
} else if (crsText && !/(4326|4258|CRS84|CRS:84)/.test(crsText)) {
|
||||
throw new Error(`sistema di coordinate non supportato (${crsText.slice(0, 80)})`);
|
||||
}
|
||||
|
||||
const normalizedCoordinates = collectGeoJsonCoordinates(root);
|
||||
if (!normalizedCoordinates.length || normalizedCoordinates.some(point =>
|
||||
!Number.isFinite(point[0])
|
||||
|| !Number.isFinite(point[1])
|
||||
|| Math.abs(point[0]) > 180
|
||||
|| Math.abs(point[1]) > 90)) {
|
||||
throw new Error("coordinate non valide o non espresse in WGS84/EPSG:4326");
|
||||
}
|
||||
|
||||
delete root.crs;
|
||||
return { geojson: root, ignoredCount: 0, reprojected: webMercator };
|
||||
}
|
||||
|
||||
function isGeoJsonGeometry(value) {
|
||||
return [
|
||||
"Point",
|
||||
"MultiPoint",
|
||||
"LineString",
|
||||
"MultiLineString",
|
||||
"Polygon",
|
||||
"MultiPolygon",
|
||||
"GeometryCollection"
|
||||
].includes(value?.type);
|
||||
}
|
||||
|
||||
function collectGeoJsonCoordinates(geojson) {
|
||||
const points = [];
|
||||
const visitGeometry = geometry => {
|
||||
if (!geometry) {
|
||||
return;
|
||||
}
|
||||
if (geometry.type === "GeometryCollection") {
|
||||
(geometry.geometries || []).forEach(visitGeometry);
|
||||
return;
|
||||
}
|
||||
const visit = coordinates => {
|
||||
if (Array.isArray(coordinates)
|
||||
&& coordinates.length >= 2
|
||||
&& typeof coordinates[0] === "number"
|
||||
&& typeof coordinates[1] === "number") {
|
||||
points.push(coordinates);
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(coordinates)) {
|
||||
coordinates.forEach(visit);
|
||||
}
|
||||
};
|
||||
visit(geometry.coordinates);
|
||||
};
|
||||
(geojson.features || []).forEach(feature => visitGeometry(feature.geometry));
|
||||
return points;
|
||||
}
|
||||
|
||||
function transformGeoJsonGeometry(geometry, transform) {
|
||||
if (!geometry) {
|
||||
return geometry;
|
||||
}
|
||||
if (geometry.type === "GeometryCollection") {
|
||||
return {
|
||||
...geometry,
|
||||
geometries: (geometry.geometries || []).map(item => transformGeoJsonGeometry(item, transform))
|
||||
};
|
||||
}
|
||||
const visit = coordinates => {
|
||||
if (Array.isArray(coordinates)
|
||||
&& coordinates.length >= 2
|
||||
&& typeof coordinates[0] === "number"
|
||||
&& typeof coordinates[1] === "number") {
|
||||
return transform(coordinates);
|
||||
}
|
||||
return Array.isArray(coordinates) ? coordinates.map(visit) : coordinates;
|
||||
};
|
||||
return { ...geometry, coordinates: visit(geometry.coordinates) };
|
||||
}
|
||||
|
||||
function webMercatorToWgs84(coordinate) {
|
||||
const longitude = coordinate[0] * 180 / 20037508.34;
|
||||
const latitudeRadians = Math.PI / 2 - 2 * Math.atan(Math.exp(-coordinate[1] / 6378137));
|
||||
return [longitude, latitudeRadians * 180 / Math.PI, ...coordinate.slice(2)];
|
||||
}
|
||||
|
||||
function normalizeKmlFiles(files) {
|
||||
const features = files.flatMap(file => kmlTextToGeoJson(file.text, file.name));
|
||||
if (!features.length) {
|
||||
throw new Error("KML senza geometrie utilizzabili");
|
||||
}
|
||||
|
||||
const selected = lmeState.importParcelOnly ? filterKmlParcelFeatures(features) : features;
|
||||
if (!selected.length) {
|
||||
throw new Error("nessuna particella trovata; disattiva 'solo particelle' per importare tutti gli elementi");
|
||||
}
|
||||
return {
|
||||
geojson: { type: "FeatureCollection", features: selected },
|
||||
ignoredCount: features.length - selected.length,
|
||||
reprojected: false
|
||||
};
|
||||
}
|
||||
|
||||
function kmlTextToGeoJson(text, sourceName) {
|
||||
const xml = new DOMParser().parseFromString(text, "text/xml");
|
||||
return toGeoJSON.kml(xml);
|
||||
if (xml.getElementsByTagName("parsererror").length) {
|
||||
throw new Error(`KML non valido (${sourceName})`);
|
||||
}
|
||||
const tree = toGeoJSON.kmlWithFolders(xml, { skipNullGeometry: true });
|
||||
const features = [];
|
||||
const visit = (node, folders) => {
|
||||
if (node?.type === "Feature") {
|
||||
node.properties = {
|
||||
...(node.properties || {}),
|
||||
_lmeFolder: folders.filter(Boolean).join(" / "),
|
||||
_lmeSource: sourceName
|
||||
};
|
||||
features.push(node);
|
||||
return;
|
||||
}
|
||||
const nextFolders = node?.type === "folder"
|
||||
? [...folders, node.meta?.name || ""]
|
||||
: folders;
|
||||
(node?.children || []).forEach(child => visit(child, nextFolders));
|
||||
};
|
||||
visit(tree, []);
|
||||
return features;
|
||||
}
|
||||
|
||||
function filterKmlParcelFeatures(features) {
|
||||
const 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") {
|
||||
return false;
|
||||
}
|
||||
const name = String(properties.name || properties.Name || properties.LABEL || "").trim();
|
||||
const identity = [name, properties.layer, properties.Layer, properties.type, properties.Tipo]
|
||||
.filter(Boolean)
|
||||
.join(" ")
|
||||
.toLowerCase();
|
||||
const folder = String(properties._lmeFolder || "").toLowerCase();
|
||||
const isParcel = /particell|mappal|parcel/.test(`${identity} ${folder}`)
|
||||
|| /^[a-z]?\s*\d+[a-z]?(?:[\/. -]\d+[a-z]?)?$/i.test(name);
|
||||
const isSheet = /\bfoglio\b|\bsheet\b|quadro[ _-]?d[' ]?unione|perimetro[ _-]?foglio/.test(identity);
|
||||
return isParcel || !isSheet;
|
||||
});
|
||||
return removeLikelySheetOutline(filtered);
|
||||
}
|
||||
|
||||
function polygonOnlyGeometry(geometry) {
|
||||
if (!geometry) {
|
||||
return null;
|
||||
}
|
||||
if (geometry.type === "Polygon" || geometry.type === "MultiPolygon") {
|
||||
return geometry;
|
||||
}
|
||||
if (geometry.type === "GeometryCollection") {
|
||||
const geometries = (geometry.geometries || []).filter(item =>
|
||||
item.type === "Polygon" || item.type === "MultiPolygon");
|
||||
return geometries.length ? { type: "GeometryCollection", geometries } : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function removeLikelySheetOutline(features) {
|
||||
if (features.length < 3) {
|
||||
return features;
|
||||
}
|
||||
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) =>
|
||||
boundsArea(item.bounds) > boundsArea(current.bounds) ? item : current);
|
||||
const others = valid.filter(item => item !== largest);
|
||||
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;
|
||||
}
|
||||
|
||||
function geoJsonBounds(geometry) {
|
||||
const wrapper = { features: [{ geometry }] };
|
||||
const points = collectGeoJsonCoordinates(wrapper);
|
||||
if (!points.length) {
|
||||
return null;
|
||||
}
|
||||
return points.reduce((bounds, point) => ({
|
||||
west: Math.min(bounds.west, point[0]),
|
||||
south: Math.min(bounds.south, point[1]),
|
||||
east: Math.max(bounds.east, point[0]),
|
||||
north: Math.max(bounds.north, point[1])
|
||||
}), { west: Infinity, south: Infinity, east: -Infinity, north: -Infinity });
|
||||
}
|
||||
|
||||
function boundsArea(bounds) {
|
||||
return Math.max(0, bounds.east - bounds.west) * Math.max(0, bounds.north - bounds.south);
|
||||
}
|
||||
|
||||
function boundsCenter(bounds) {
|
||||
return [(bounds.west + bounds.east) / 2, (bounds.south + bounds.north) / 2];
|
||||
}
|
||||
|
||||
function boundsContains(bounds, point) {
|
||||
return point[0] >= bounds.west && point[0] <= bounds.east
|
||||
&& point[1] >= bounds.south && point[1] <= bounds.north;
|
||||
}
|
||||
|
||||
function 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 setImportedMeasurementsVisible(enabled) {
|
||||
lmeState.showImportedMeasurements = Boolean(enabled);
|
||||
refreshImportedMeasurements();
|
||||
setInfo(lmeState.showImportedMeasurements
|
||||
? "Misure dei file GIS visibili."
|
||||
: "Misure dei file GIS nascoste.");
|
||||
}
|
||||
|
||||
function setDrawingMeasurementsVisible(enabled) {
|
||||
lmeState.showDrawingMeasurements = Boolean(enabled);
|
||||
refreshDrawingMeasurements();
|
||||
setInfo(lmeState.showDrawingMeasurements
|
||||
? "Misure dei disegni visibili."
|
||||
: "Misure dei disegni nascoste.");
|
||||
}
|
||||
|
||||
function fitImported() {
|
||||
@@ -451,6 +803,7 @@ function fitImported() {
|
||||
|
||||
function clearImported() {
|
||||
lmeState.imported.clearLayers();
|
||||
lmeState.importedMeasurements.clearLayers();
|
||||
setInfo("File GIS rimossi.");
|
||||
updateGpsInsideState();
|
||||
}
|
||||
@@ -459,7 +812,12 @@ function addProjectMarker(name) {
|
||||
const center = lmeState.map.getCenter();
|
||||
const label = (name || "Nuovo POI").trim();
|
||||
const marker = L.marker(center, { draggable: true }).addTo(lmeState.drawings);
|
||||
marker.feature = {
|
||||
type: "Feature",
|
||||
properties: { name: label }
|
||||
};
|
||||
marker.bindPopup(`<strong>${escapeHtml(label)}</strong><br>${center.lat.toFixed(6)}, ${center.lng.toFixed(6)}`).openPopup();
|
||||
refreshDrawingMeasurements();
|
||||
setInfo(`POI aggiunto: ${label}`);
|
||||
}
|
||||
|
||||
@@ -473,25 +831,107 @@ function enableDrawTools() {
|
||||
position: "topright",
|
||||
edit: { featureGroup: lmeState.drawings },
|
||||
draw: {
|
||||
circle: false,
|
||||
circle: { metric: true, feet: false },
|
||||
circlemarker: false,
|
||||
marker: true,
|
||||
polygon: true,
|
||||
polyline: true,
|
||||
polygon: { metric: true, feet: false, showArea: true, allowIntersection: false },
|
||||
polyline: { metric: true, feet: false, showLength: true },
|
||||
rectangle: true
|
||||
}
|
||||
});
|
||||
lmeState.map.addControl(lmeState.drawControl);
|
||||
if (!lmeState.drawEventsBound) {
|
||||
lmeState.map.on(L.Draw.Event.CREATED, event => {
|
||||
annotateDrawingLayer(event.layer, event.layerType);
|
||||
lmeState.drawings.addLayer(event.layer);
|
||||
refreshDrawingMeasurements();
|
||||
updateGpsInsideState();
|
||||
const completedLabels = {
|
||||
polygon: "Area completata: superficie, perimetro e lati aggiornati.",
|
||||
rectangle: "Rettangolo completato: superficie, perimetro e lati aggiornati.",
|
||||
polyline: "Distanza completata: lunghezza totale e tratti aggiornati.",
|
||||
circle: "Cerchio completato: superficie, raggio e circonferenza aggiornati.",
|
||||
marker: "Punto aggiunto alla mappa."
|
||||
};
|
||||
setInfo(completedLabels[event.layerType] || "Disegno completato.");
|
||||
});
|
||||
lmeState.map.on(L.Draw.Event.EDITED, event => {
|
||||
event.layers.eachLayer(layer => annotateDrawingLayer(layer));
|
||||
refreshDrawingMeasurements();
|
||||
updateGpsInsideState();
|
||||
});
|
||||
lmeState.map.on(L.Draw.Event.DELETED, () => {
|
||||
refreshDrawingMeasurements();
|
||||
updateGpsInsideState();
|
||||
});
|
||||
lmeState.map.on(L.Draw.Event.DRAWSTOP, () => {
|
||||
lmeState.activeDrawHandler = null;
|
||||
});
|
||||
lmeState.drawEventsBound = true;
|
||||
}
|
||||
setInfo("Disegno attivo: crea POI, linee e aree sulla mappa.");
|
||||
}
|
||||
|
||||
function startMeasurementDrawing(mode) {
|
||||
if (!lmeState.map) {
|
||||
return;
|
||||
}
|
||||
if (!lmeState.drawEventsBound) {
|
||||
enableDrawTools();
|
||||
setDrawToolsVisible(false);
|
||||
}
|
||||
if (lmeState.activeDrawHandler) {
|
||||
lmeState.activeDrawHandler.disable();
|
||||
}
|
||||
|
||||
const handlers = {
|
||||
area: () => new L.Draw.Polygon(lmeState.map, {
|
||||
allowIntersection: false,
|
||||
showArea: true,
|
||||
metric: true,
|
||||
feet: false,
|
||||
shapeOptions: { color: "#f97316", weight: 4, fillColor: "#fb923c", fillOpacity: 0.2 }
|
||||
}),
|
||||
distance: () => new L.Draw.Polyline(lmeState.map, {
|
||||
metric: true,
|
||||
feet: false,
|
||||
showLength: true,
|
||||
shapeOptions: { color: "#f97316", weight: 4, opacity: 0.95 }
|
||||
}),
|
||||
circle: () => new L.Draw.Circle(lmeState.map, {
|
||||
metric: true,
|
||||
feet: false,
|
||||
showRadius: true,
|
||||
shapeOptions: { color: "#f97316", weight: 4, fillColor: "#fb923c", fillOpacity: 0.2 }
|
||||
})
|
||||
};
|
||||
const createHandler = handlers[mode];
|
||||
if (!createHandler) {
|
||||
setInfo("Modalita di misura non riconosciuta.");
|
||||
return;
|
||||
}
|
||||
|
||||
lmeState.activeDrawHandler = createHandler();
|
||||
lmeState.activeDrawHandler.enable();
|
||||
const labels = {
|
||||
area: "Tocca i vertici dell'area; chiudi toccando il primo punto.",
|
||||
distance: "Tocca i punti del percorso; termina sull'ultimo punto.",
|
||||
circle: "Tocca il centro e trascina fino al raggio desiderato."
|
||||
};
|
||||
setInfo(labels[mode]);
|
||||
}
|
||||
|
||||
function annotateDrawingLayer(layer, layerType) {
|
||||
layer.feature = layer.feature || { type: "Feature", properties: {} };
|
||||
layer.feature.properties = layer.feature.properties || {};
|
||||
if (layer instanceof L.Circle) {
|
||||
layer.feature.properties._lmeShape = "circle";
|
||||
layer.feature.properties._lmeRadius = layer.getRadius();
|
||||
} else if (layerType) {
|
||||
layer.feature.properties._lmeShape = layerType;
|
||||
}
|
||||
}
|
||||
|
||||
function setDrawToolsVisible(visible) {
|
||||
if (visible) {
|
||||
enableDrawTools();
|
||||
@@ -524,37 +964,363 @@ function clearDrawings() {
|
||||
}
|
||||
|
||||
lmeState.drawings.clearLayers();
|
||||
lmeState.drawingMeasurements.clearLayers();
|
||||
updateGpsInsideState();
|
||||
setInfo("Disegni e POI eliminati dalla mappa.");
|
||||
}
|
||||
|
||||
function saveWorkspace() {
|
||||
const data = {
|
||||
drawings: lmeState.drawings.toGeoJSON(),
|
||||
imported: lmeState.imported.toGeoJSON(),
|
||||
trail: lmeState.gpsTrailPoints
|
||||
};
|
||||
localStorage.setItem("lmeMapWorkspace", JSON.stringify(data));
|
||||
setInfo("Progetti, POI, file e percorso salvati sul dispositivo.");
|
||||
function scheduleMeasurementRefresh() {
|
||||
window.clearTimeout(lmeState.measurementRefreshTimer);
|
||||
lmeState.measurementRefreshTimer = window.setTimeout(() => {
|
||||
refreshImportedMeasurements();
|
||||
refreshDrawingMeasurements();
|
||||
}, 80);
|
||||
}
|
||||
|
||||
function loadWorkspace() {
|
||||
const raw = localStorage.getItem("lmeMapWorkspace");
|
||||
if (!raw) {
|
||||
setInfo("Nessun progetto salvato trovato.");
|
||||
function refreshImportedMeasurements() {
|
||||
renderMeasurements(
|
||||
lmeState.imported,
|
||||
lmeState.importedMeasurements,
|
||||
lmeState.showImportedMeasurements,
|
||||
"imported");
|
||||
}
|
||||
|
||||
function refreshDrawingMeasurements() {
|
||||
renderMeasurements(
|
||||
lmeState.drawings,
|
||||
lmeState.drawingMeasurements,
|
||||
lmeState.showDrawingMeasurements,
|
||||
"drawing");
|
||||
}
|
||||
|
||||
function renderMeasurements(sourceGroup, targetGroup, visible, sourceType) {
|
||||
if (!sourceGroup || !targetGroup) {
|
||||
return;
|
||||
}
|
||||
targetGroup.clearLayers();
|
||||
if (!visible) {
|
||||
return;
|
||||
}
|
||||
|
||||
const data = JSON.parse(raw);
|
||||
lmeState.drawings.clearLayers();
|
||||
lmeState.imported.clearLayers();
|
||||
L.geoJSON(data.drawings, { style: { color: "#f97316", weight: 3, fillOpacity: 0.16 } }).addTo(lmeState.drawings);
|
||||
L.geoJSON(data.imported, { style: { color: "#22c55e", weight: 3, fillOpacity: 0.18 } }).addTo(lmeState.imported);
|
||||
lmeState.gpsTrailPoints = data.trail || [];
|
||||
lmeState.gpsTrail.setLatLngs(lmeState.gpsTrailPoints);
|
||||
fitLayer(L.featureGroup([lmeState.drawings, lmeState.imported]));
|
||||
updateGpsInsideState();
|
||||
setInfo("Progetto caricato.");
|
||||
const context = {
|
||||
count: 0,
|
||||
max: 600,
|
||||
showSides: lmeState.map.getZoom() >= 17,
|
||||
bounds: lmeState.map.getBounds(),
|
||||
sourceType
|
||||
};
|
||||
visitMeasurableLayers(sourceGroup, layer => {
|
||||
if (context.count >= context.max || !layerIsInView(layer, context.bounds)) {
|
||||
return;
|
||||
}
|
||||
if (layer instanceof L.Circle) {
|
||||
renderCircleMeasurement(layer, targetGroup, context);
|
||||
} else if (layer instanceof L.Polygon) {
|
||||
renderPolygonMeasurement(layer, targetGroup, context);
|
||||
} else if (layer instanceof L.Polyline) {
|
||||
renderPolylineMeasurement(layer, targetGroup, context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function visitMeasurableLayers(layer, visitor) {
|
||||
if (layer instanceof L.Circle || layer instanceof L.Polygon || layer instanceof L.Polyline) {
|
||||
visitor(layer);
|
||||
return;
|
||||
}
|
||||
if (typeof layer.eachLayer === "function") {
|
||||
layer.eachLayer(child => visitMeasurableLayers(child, visitor));
|
||||
}
|
||||
}
|
||||
|
||||
function layerIsInView(layer, mapBounds) {
|
||||
if (typeof layer.getBounds === "function") {
|
||||
const bounds = layer.getBounds();
|
||||
return !bounds.isValid || !bounds.isValid() || bounds.intersects(mapBounds);
|
||||
}
|
||||
if (typeof layer.getLatLng === "function") {
|
||||
return mapBounds.contains(layer.getLatLng());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function renderCircleMeasurement(layer, targetGroup, context) {
|
||||
const radius = layer.getRadius();
|
||||
const area = Math.PI * radius * radius;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
addMeasurementLabel(
|
||||
targetGroup,
|
||||
layer.getLatLng(),
|
||||
`S: ${formatArea(area)}<br>R: ${formatDistance(radius)} · C: ${formatDistance(circumference)}`,
|
||||
"summary",
|
||||
context);
|
||||
}
|
||||
|
||||
function renderPolygonMeasurement(layer, targetGroup, context) {
|
||||
const polygons = polygonLatLngGroups(layer.getLatLngs());
|
||||
let area = 0;
|
||||
let perimeter = 0;
|
||||
polygons.forEach(rings => {
|
||||
rings.forEach((ring, index) => {
|
||||
const ringArea = Math.abs(L.GeometryUtil.geodesicArea(ring));
|
||||
area += index === 0 ? ringArea : -ringArea;
|
||||
perimeter += latLngPathLength(ring, true);
|
||||
if (context.showSides) {
|
||||
addSegmentLabels(ring, true, targetGroup, context);
|
||||
}
|
||||
});
|
||||
});
|
||||
const center = typeof layer.getCenter === "function"
|
||||
? layer.getCenter()
|
||||
: layer.getBounds().getCenter();
|
||||
addMeasurementLabel(
|
||||
targetGroup,
|
||||
center,
|
||||
`S: ${formatArea(Math.max(0, area))}<br>P: ${formatDistance(perimeter)}`,
|
||||
"summary",
|
||||
context);
|
||||
}
|
||||
|
||||
function renderPolylineMeasurement(layer, targetGroup, context) {
|
||||
const lines = lineLatLngGroups(layer.getLatLngs());
|
||||
const length = lines.reduce((total, line) => total + latLngPathLength(line, false), 0);
|
||||
if (context.showSides) {
|
||||
lines.forEach(line => addSegmentLabels(line, false, targetGroup, context));
|
||||
}
|
||||
const longest = lines.reduce((current, line) => line.length > current.length ? line : current, []);
|
||||
if (longest.length) {
|
||||
addMeasurementLabel(
|
||||
targetGroup,
|
||||
longest[Math.floor(longest.length / 2)],
|
||||
`L: ${formatDistance(length)}`,
|
||||
"summary",
|
||||
context);
|
||||
}
|
||||
}
|
||||
|
||||
function polygonLatLngGroups(latLngs) {
|
||||
if (!Array.isArray(latLngs) || !latLngs.length) {
|
||||
return [];
|
||||
}
|
||||
if (isLatLng(latLngs[0])) {
|
||||
return [[latLngs]];
|
||||
}
|
||||
if (Array.isArray(latLngs[0]) && isLatLng(latLngs[0][0])) {
|
||||
return [latLngs];
|
||||
}
|
||||
return latLngs.flatMap(polygonLatLngGroups);
|
||||
}
|
||||
|
||||
function lineLatLngGroups(latLngs) {
|
||||
if (!Array.isArray(latLngs) || !latLngs.length) {
|
||||
return [];
|
||||
}
|
||||
if (isLatLng(latLngs[0])) {
|
||||
return [latLngs];
|
||||
}
|
||||
return latLngs.flatMap(lineLatLngGroups);
|
||||
}
|
||||
|
||||
function isLatLng(value) {
|
||||
return value && Number.isFinite(value.lat) && Number.isFinite(value.lng);
|
||||
}
|
||||
|
||||
function latLngPathLength(points, closed) {
|
||||
if (points.length < 2) {
|
||||
return 0;
|
||||
}
|
||||
let total = 0;
|
||||
for (let index = 1; index < points.length; index += 1) {
|
||||
total += lmeState.map.distance(points[index - 1], points[index]);
|
||||
}
|
||||
if (closed && !points[0].equals(points[points.length - 1])) {
|
||||
total += lmeState.map.distance(points[points.length - 1], points[0]);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function addSegmentLabels(points, closed, targetGroup, context) {
|
||||
if (points.length < 2) {
|
||||
return;
|
||||
}
|
||||
const segmentCount = closed ? points.length : points.length - 1;
|
||||
for (let index = 0; index < segmentCount && context.count < context.max; index += 1) {
|
||||
const start = points[index];
|
||||
const end = points[(index + 1) % points.length];
|
||||
if (start.equals(end)) {
|
||||
continue;
|
||||
}
|
||||
addMeasurementLabel(
|
||||
targetGroup,
|
||||
L.latLng((start.lat + end.lat) / 2, (start.lng + end.lng) / 2),
|
||||
formatDistance(lmeState.map.distance(start, end)),
|
||||
"side",
|
||||
context);
|
||||
}
|
||||
}
|
||||
|
||||
function addMeasurementLabel(targetGroup, latLng, html, labelType, context) {
|
||||
if (context.count >= context.max) {
|
||||
return;
|
||||
}
|
||||
L.marker(latLng, {
|
||||
interactive: false,
|
||||
keyboard: false,
|
||||
icon: L.divIcon({
|
||||
className: `lme-measure-label ${context.sourceType} ${labelType}`,
|
||||
html: `<span>${html}</span>`,
|
||||
iconSize: null
|
||||
})
|
||||
}).addTo(targetGroup);
|
||||
context.count += 1;
|
||||
}
|
||||
|
||||
function formatDistance(meters) {
|
||||
if (meters >= 1000) {
|
||||
return `${formatNumber(meters / 1000, 3)} km`;
|
||||
}
|
||||
return `${formatNumber(meters, meters < 100 ? 1 : 0)} m`;
|
||||
}
|
||||
|
||||
function formatArea(squareMeters) {
|
||||
if (squareMeters >= 10000) {
|
||||
return `${formatNumber(squareMeters / 10000, 4)} ha`;
|
||||
}
|
||||
return `${formatNumber(squareMeters, squareMeters < 100 ? 1 : 0)} m²`;
|
||||
}
|
||||
|
||||
function formatNumber(value, digits) {
|
||||
return new Intl.NumberFormat("it-IT", {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: digits
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
function createProjectSnapshot(includeCadastralParcels) {
|
||||
const center = lmeState.map.getCenter();
|
||||
return JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
view: {
|
||||
latitude: center.lat,
|
||||
longitude: center.lng,
|
||||
zoom: lmeState.map.getZoom()
|
||||
},
|
||||
drawings: lmeState.drawings.toGeoJSON(),
|
||||
imported: lmeState.imported.toGeoJSON(),
|
||||
selectedParcels: includeCadastralParcels
|
||||
? lmeState.selectedParcelsLayer.toGeoJSON()
|
||||
: { type: "FeatureCollection", features: [] },
|
||||
trail: lmeState.gpsTrailPoints.map(point => [
|
||||
Number(point.lat ?? point[0]),
|
||||
Number(point.lng ?? point[1])
|
||||
])
|
||||
});
|
||||
}
|
||||
|
||||
function getLegacyProjectSnapshot() {
|
||||
return localStorage.getItem("lmeMapWorkspace");
|
||||
}
|
||||
|
||||
function clearLegacyProjectSnapshot() {
|
||||
localStorage.removeItem("lmeMapWorkspace");
|
||||
}
|
||||
|
||||
function loadProjectSnapshot(raw, projectName) {
|
||||
try {
|
||||
const data = typeof raw === "string" ? JSON.parse(raw) : raw;
|
||||
if (!data || typeof data !== "object") {
|
||||
throw new Error("contenuto non valido");
|
||||
}
|
||||
|
||||
lmeState.drawings.clearLayers();
|
||||
lmeState.imported.clearLayers();
|
||||
lmeState.drawingMeasurements.clearLayers();
|
||||
lmeState.importedMeasurements.clearLayers();
|
||||
lmeState.selectedParcelsLayer.clearLayers();
|
||||
lmeState.gpsParcelLayer.clearLayers();
|
||||
|
||||
const restoredDrawings = L.geoJSON(data.drawings || emptyFeatureCollection(), {
|
||||
style: { color: "#f97316", weight: 3, fillOpacity: 0.16 },
|
||||
pointToLayer: (feature, latlng) => {
|
||||
const properties = feature?.properties || {};
|
||||
if (properties._lmeShape === "circle" && Number(properties._lmeRadius) > 0) {
|
||||
return L.circle(latlng, {
|
||||
radius: Number(properties._lmeRadius),
|
||||
color: "#f97316",
|
||||
weight: 3,
|
||||
fillColor: "#fb923c",
|
||||
fillOpacity: 0.2
|
||||
});
|
||||
}
|
||||
return L.marker(latlng, { draggable: true });
|
||||
},
|
||||
onEachFeature: bindStoredFeaturePopup
|
||||
});
|
||||
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);
|
||||
L.geoJSON(data.selectedParcels || emptyFeatureCollection(), {
|
||||
style: { color: "#ef4444", weight: 4, opacity: 1, fillColor: "#fbbf24", fillOpacity: 0.26 },
|
||||
onEachFeature: (feature, layer) => {
|
||||
const properties = feature?.properties || {};
|
||||
const reference = properties.NATIONALCADASTRALREFERENCE
|
||||
|| properties.INSPIREID_LOCALID
|
||||
|| properties.LABEL
|
||||
|| "Particella catastale";
|
||||
layer.lmeParcelReference = reference;
|
||||
layer.bindPopup(`<strong>${escapeHtml(reference)}</strong>`);
|
||||
}
|
||||
}).addTo(lmeState.selectedParcelsLayer);
|
||||
|
||||
lmeState.gpsTrailPoints = Array.isArray(data.trail) ? data.trail : [];
|
||||
lmeState.gpsTrail.setLatLngs(lmeState.gpsTrailPoints);
|
||||
refreshImportedMeasurements();
|
||||
refreshDrawingMeasurements();
|
||||
|
||||
const projectLayers = L.featureGroup([
|
||||
lmeState.drawings,
|
||||
lmeState.imported,
|
||||
lmeState.selectedParcelsLayer,
|
||||
lmeState.gpsTrail
|
||||
]);
|
||||
if (projectLayers.getBounds().isValid()) {
|
||||
fitLayer(projectLayers);
|
||||
} else if (Number.isFinite(data.view?.latitude)
|
||||
&& Number.isFinite(data.view?.longitude)
|
||||
&& Number.isFinite(data.view?.zoom)) {
|
||||
lmeState.map.setView([data.view.latitude, data.view.longitude], data.view.zoom);
|
||||
}
|
||||
|
||||
const parcelCount = lmeState.selectedParcelsLayer.toGeoJSON().features?.length || 0;
|
||||
setText("parcelState", parcelCount
|
||||
? `${parcelCount} particelle del progetto`
|
||||
: "Nessuna particella selezionata");
|
||||
updateGpsInsideState();
|
||||
setInfo(`Progetto caricato: ${projectName || "senza nome"}.`);
|
||||
} catch (error) {
|
||||
setInfo(`Progetto non leggibile: ${error.message}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function emptyFeatureCollection() {
|
||||
return { type: "FeatureCollection", features: [] };
|
||||
}
|
||||
|
||||
function bindStoredFeaturePopup(feature, layer) {
|
||||
const properties = feature?.properties || {};
|
||||
const label = properties.name || properties.Name || properties.label || properties.LABEL;
|
||||
if (label) {
|
||||
layer.bindPopup(`<strong>${escapeHtml(label)}</strong>`);
|
||||
}
|
||||
}
|
||||
|
||||
function setBaseLayer(name) {
|
||||
@@ -853,6 +1619,8 @@ function clearMapElements() {
|
||||
lmeState.gpsParcelLayer.clearLayers();
|
||||
lmeState.imported.clearLayers();
|
||||
lmeState.drawings.clearLayers();
|
||||
lmeState.importedMeasurements.clearLayers();
|
||||
lmeState.drawingMeasurements.clearLayers();
|
||||
lmeState.gpsTrailPoints = [];
|
||||
lmeState.gpsTrail.setLatLngs([]);
|
||||
updateGpsInsideState();
|
||||
|
||||
Reference in new issue
Block a user