Rilascia strumenti avanzati e archivio 0.3.0
This commit is contained in:
1 parent
b19afbce91
commit
2a462b205c
8 files changed
+1351
-33
No files matched your search
+208
-4
@@ -211,6 +211,10 @@
|
||||
|
||||
<section class="panel-section">
|
||||
<h2>Disegni e misure</h2>
|
||||
<div class="button-row">
|
||||
<button class="secondary-command" @onclick="UndoMapChange">Annulla</button>
|
||||
<button class="secondary-command" @onclick="RedoMapChange">Ripristina</button>
|
||||
</div>
|
||||
<label class="toggle-line project-save-option">
|
||||
<input type="checkbox" @bind="ShowDrawingMeasurements" @bind:after="ApplyDrawingMeasurementsVisibility" />
|
||||
<span>Mostra superficie, perimetro e lati</span>
|
||||
@@ -219,6 +223,7 @@
|
||||
@(DrawToolsVisible ? "Nascondi strumenti sulla mappa" : "Mostra strumenti sulla mappa")
|
||||
</button>
|
||||
<button class="danger-command" @onclick="ClearDrawings">Elimina disegni e POI</button>
|
||||
<button class="secondary-command" @onclick="RestoreAutosave">Recupera ultimo autosalvataggio</button>
|
||||
</section>
|
||||
|
||||
<section class="panel-section">
|
||||
@@ -246,9 +251,15 @@
|
||||
<option value="geojson">GeoJSON</option>
|
||||
<option value="kml">KML</option>
|
||||
<option value="kmz">KMZ compresso</option>
|
||||
<option value="gpx">GPX per GPS</option>
|
||||
<option value="pdf">Rapporto PDF</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="ExportSelectedOnly" @bind:after="SaveFlagPreferences" />
|
||||
<span>Solo oggetti selezionati nel pannello Layer</span>
|
||||
</label>
|
||||
<label class="toggle-line project-save-option">
|
||||
<input type="checkbox" @bind="ExportImported" @bind:after="SaveFlagPreferences" />
|
||||
<span>Particelle e dati GIS importati</span>
|
||||
@@ -306,7 +317,7 @@
|
||||
<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>
|
||||
<option value="@project.Id">@(project.IsArchived ? "[ARCHIVIATO] " : "")@(string.IsNullOrWhiteSpace(project.Folder) ? "" : $"{project.Folder} / ")@project.Name - @project.UpdatedAt.ToLocalTime().ToString("dd/MM/yyyy HH:mm")</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
@@ -314,9 +325,44 @@
|
||||
<button @onclick="LoadProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Apri</button>
|
||||
<button class="danger-command" @onclick="DeleteProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Elimina</button>
|
||||
</div>
|
||||
<label>
|
||||
Cartella
|
||||
<input @bind="ProjectFolder" placeholder="Es. Cantieri 2026" maxlength="60" />
|
||||
</label>
|
||||
<div class="button-row">
|
||||
<button class="secondary-command" @onclick="UpdateProjectFolder" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Sposta</button>
|
||||
<button class="secondary-command" @onclick="DuplicateProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Duplica</button>
|
||||
</div>
|
||||
<div class="button-row">
|
||||
<button class="secondary-command" @onclick="ToggleProjectArchive" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">@(SelectedProject?.IsArchived == true ? "Ripristina" : "Archivia")</button>
|
||||
<button class="secondary-command" @onclick="ShareProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Condividi</button>
|
||||
</div>
|
||||
<label>
|
||||
Revisione precedente
|
||||
<select @bind="SelectedVersionId" disabled="@(ProjectVersions.Count == 0)">
|
||||
<option value="">Seleziona revisione</option>
|
||||
@foreach (var version in ProjectVersions)
|
||||
{
|
||||
<option value="@version.Id">@version.UpdatedAt.ToLocalTime().ToString("dd/MM/yyyy HH:mm:ss")</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<div class="button-row">
|
||||
<button class="secondary-command" @onclick="LoadProjectVersion" disabled="@(string.IsNullOrWhiteSpace(SelectedVersionId))">Apri revisione</button>
|
||||
<button class="secondary-command" @onclick="CompareProjectVersion" disabled="@(string.IsNullOrWhiteSpace(SelectedVersionId))">Confronta</button>
|
||||
</div>
|
||||
<div class="project-archive-state">@ProjectArchiveMessage</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-section">
|
||||
<h2>Backup e trasferimento</h2>
|
||||
<div class="button-row">
|
||||
<button class="secondary-command" @onclick="ShareFullBackup">Crea backup</button>
|
||||
<button class="secondary-command" @onclick="RestoreBackup">Ripristina backup</button>
|
||||
</div>
|
||||
<button class="secondary-command" @onclick="ImportProject">Importa progetto condiviso</button>
|
||||
</section>
|
||||
|
||||
<section class="panel-section">
|
||||
<h2>Visualizzazione progetto</h2>
|
||||
<label class="toggle-line project-save-option">
|
||||
@@ -353,6 +399,7 @@
|
||||
<option value="topographic">Topografica - Esri World Topographic</option>
|
||||
<option value="terrain">Terreno - OpenTopoMap</option>
|
||||
<option value="carto">Strade chiare - CARTO Voyager</option>
|
||||
<option value="offline">Offline - solo dati vettoriali</option>
|
||||
<option value="azure-road">Strade - Azure Maps</option>
|
||||
<option value="azure-satellite">Satellite - Azure Maps</option>
|
||||
<option value="google-satellite">Satellite - Google Maps</option>
|
||||
@@ -383,6 +430,22 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-section">
|
||||
<h2>Modifica e sicurezza dati</h2>
|
||||
<label class="toggle-line project-save-option">
|
||||
<input type="checkbox" @bind="AutoSaveEnabled" @bind:after="ApplyAdvancedOptions" />
|
||||
<span>Autosalvataggio locale dopo ogni modifica</span>
|
||||
</label>
|
||||
<label class="toggle-line project-save-option">
|
||||
<input type="checkbox" @bind="SnapEnabled" @bind:after="ApplyAdvancedOptions" />
|
||||
<span>Aggancia i vertici agli oggetti vicini</span>
|
||||
</label>
|
||||
<label>
|
||||
Distanza aggancio in pixel
|
||||
<input type="range" min="4" max="40" step="1" @bind="SnapDistancePixels" @bind:after="ApplyAdvancedOptions" />
|
||||
</label>
|
||||
</section>
|
||||
|
||||
<section class="panel-section">
|
||||
<h2>GPS e percorso</h2>
|
||||
<label class="toggle-line project-save-option">
|
||||
@@ -393,6 +456,15 @@
|
||||
<input type="checkbox" @bind="TrailEnabled" @bind:after="ApplyTrailOption" />
|
||||
<span>Registra la traccia mentre cammini</span>
|
||||
</label>
|
||||
<label class="toggle-line project-save-option">
|
||||
<input type="checkbox" @bind="GpsProximityEnabled" @bind:after="ApplyAdvancedOptions" />
|
||||
<span>Distanza e direzione dal bordo selezionato</span>
|
||||
</label>
|
||||
<label class="toggle-line project-save-option">
|
||||
<input type="checkbox" @bind="GpsBoundaryAlertEnabled" @bind:after="ApplyAdvancedOptions" />
|
||||
<span>Avvisa quando entro o esco dall'area selezionata</span>
|
||||
</label>
|
||||
<button class="secondary-command" @onclick="SaveGpsMeasurementPoint">Salva punto GPS con precisione e ora</button>
|
||||
</section>
|
||||
|
||||
<section class="panel-section">
|
||||
@@ -453,6 +525,8 @@
|
||||
private string PoiName { get; set; } = string.Empty;
|
||||
private string SelectedProjectId { get; set; } = string.Empty;
|
||||
private string ProjectArchiveMessage { get; set; } = "Nessun progetto salvato.";
|
||||
private string ProjectFolder { get; set; } = string.Empty;
|
||||
private string SelectedVersionId { get; set; } = string.Empty;
|
||||
private string Status { get; set; } = "online";
|
||||
private string SelectedBaseLayer { get; set; } = "satellite";
|
||||
private string GoogleMapsApiKey { get; set; } = string.Empty;
|
||||
@@ -486,6 +560,12 @@
|
||||
private bool ExportDrawings { get; set; } = true;
|
||||
private bool ExportPoi { get; set; } = true;
|
||||
private bool ExportTrail { get; set; } = true;
|
||||
private bool ExportSelectedOnly { get; set; }
|
||||
private bool AutoSaveEnabled { get; set; } = true;
|
||||
private bool SnapEnabled { get; set; } = true;
|
||||
private int SnapDistancePixels { get; set; } = 14;
|
||||
private bool GpsProximityEnabled { get; set; } = true;
|
||||
private bool GpsBoundaryAlertEnabled { get; set; }
|
||||
private CancellationTokenSource? CatalogCancellation { get; set; }
|
||||
private CancellationTokenSource? GpsLookupCancellation { get; set; }
|
||||
private long LastGpsLookupAt;
|
||||
@@ -496,6 +576,8 @@
|
||||
private IReadOnlyList<string> Sheets { get; set; } = [];
|
||||
private IReadOnlyList<ParcelOption> Parcels { get; set; } = [];
|
||||
private IReadOnlyList<MapProjectSummary> Projects { get; set; } = [];
|
||||
private IReadOnlyList<MapProjectVersion> ProjectVersions { get; set; } = [];
|
||||
private MapProjectSummary? SelectedProject => Projects.FirstOrDefault(item => item.Id == SelectedProjectId);
|
||||
|
||||
private MunicipalityOption? SelectedMunicipality =>
|
||||
Municipalities.FirstOrDefault(item => item.Code == SelectedMunicipalityCode);
|
||||
@@ -574,6 +656,7 @@
|
||||
MapCallbackReference = DotNetObjectReference.Create(this);
|
||||
await JS.InvokeVoidAsync("lmeMap.init", MapCallbackReference);
|
||||
await ApplyFlagPreferencesToMapAsync();
|
||||
await ApplyAdvancedOptions();
|
||||
await CenterOnInitialLocationAsync();
|
||||
await MigrateLegacyProjectAsync();
|
||||
}
|
||||
@@ -1097,10 +1180,105 @@
|
||||
}
|
||||
}
|
||||
|
||||
private Task SelectProject(ChangeEventArgs args)
|
||||
private async Task SelectProject(ChangeEventArgs args)
|
||||
{
|
||||
SelectedProjectId = args.Value?.ToString() ?? string.Empty;
|
||||
return Task.CompletedTask;
|
||||
ProjectFolder = SelectedProject?.Folder ?? string.Empty;
|
||||
SelectedVersionId = string.Empty;
|
||||
ProjectVersions = string.IsNullOrWhiteSpace(SelectedProjectId)
|
||||
? []
|
||||
: await ProjectStorageService.GetVersionsAsync(SelectedProjectId);
|
||||
}
|
||||
|
||||
private Task UndoMapChange() => JS.InvokeVoidAsync("lmeMap.undoMapChange").AsTask();
|
||||
private Task RedoMapChange() => JS.InvokeVoidAsync("lmeMap.redoMapChange").AsTask();
|
||||
private Task RestoreAutosave() => JS.InvokeVoidAsync("lmeMap.restoreAutosave").AsTask();
|
||||
private Task SaveGpsMeasurementPoint() => JS.InvokeVoidAsync("lmeMap.saveGpsMeasurementPoint").AsTask();
|
||||
|
||||
private async Task DuplicateProject()
|
||||
{
|
||||
if (SelectedProject is null) return;
|
||||
var copy = await ProjectStorageService.DuplicateAsync(SelectedProject.Id);
|
||||
await RefreshProjectsAsync();
|
||||
SelectedProjectId = copy.Id;
|
||||
ProjectFolder = copy.Folder;
|
||||
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Progetto duplicato: {copy.Name}.");
|
||||
}
|
||||
|
||||
private async Task UpdateProjectFolder()
|
||||
{
|
||||
if (SelectedProject is null) return;
|
||||
await ProjectStorageService.UpdateOrganizationAsync(SelectedProject.Id, ProjectFolder);
|
||||
await RefreshProjectsAsync();
|
||||
await JS.InvokeVoidAsync("lmeMap.showInfo", "Cartella del progetto aggiornata.");
|
||||
}
|
||||
|
||||
private async Task ToggleProjectArchive()
|
||||
{
|
||||
if (SelectedProject is not { } project) return;
|
||||
await ProjectStorageService.UpdateOrganizationAsync(project.Id, isArchived: !project.IsArchived);
|
||||
await RefreshProjectsAsync();
|
||||
await JS.InvokeVoidAsync("lmeMap.showInfo", project.IsArchived ? "Progetto ripristinato." : "Progetto archiviato.");
|
||||
}
|
||||
|
||||
private async Task ShareProject()
|
||||
{
|
||||
if (SelectedProject is null) return;
|
||||
var path = await ProjectStorageService.CreateProjectPackageAsync(SelectedProject.Id);
|
||||
await Share.Default.RequestAsync(new ShareFileRequest { Title = "Condividi progetto LME", File = new ShareFile(path, "application/json") });
|
||||
}
|
||||
|
||||
private async Task ShareFullBackup()
|
||||
{
|
||||
var path = await ProjectStorageService.CreateBackupAsync();
|
||||
await Share.Default.RequestAsync(new ShareFileRequest { Title = "Backup completo LME Mappe Catastali", File = new ShareFile(path, "application/zip") });
|
||||
}
|
||||
|
||||
private async Task RestoreBackup()
|
||||
{
|
||||
var file = await FilePicker.Default.PickAsync(new PickOptions { PickerTitle = "Scegli backup LME" });
|
||||
if (file is null) return;
|
||||
var path = await CopyPickedFileToCacheAsync(file);
|
||||
var count = await ProjectStorageService.RestoreBackupAsync(path);
|
||||
await RefreshProjectsAsync();
|
||||
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Backup ripristinato: {count} progetti disponibili.");
|
||||
}
|
||||
|
||||
private async Task ImportProject()
|
||||
{
|
||||
var file = await FilePicker.Default.PickAsync(new PickOptions { PickerTitle = "Scegli progetto LME" });
|
||||
if (file is null) return;
|
||||
var path = await CopyPickedFileToCacheAsync(file);
|
||||
var imported = await ProjectStorageService.ImportProjectAsync(path);
|
||||
await RefreshProjectsAsync();
|
||||
SelectedProjectId = imported.Id;
|
||||
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Progetto importato: {imported.Name}.");
|
||||
}
|
||||
|
||||
private static async Task<string> CopyPickedFileToCacheAsync(FileResult file)
|
||||
{
|
||||
var path = Path.Combine(FileSystem.CacheDirectory, $"{Guid.NewGuid():N}-{file.FileName}");
|
||||
await using var input = await file.OpenReadAsync();
|
||||
await using var output = File.Create(path);
|
||||
await input.CopyToAsync(output);
|
||||
return path;
|
||||
}
|
||||
|
||||
private async Task LoadProjectVersion()
|
||||
{
|
||||
if (SelectedProject is null || string.IsNullOrWhiteSpace(SelectedVersionId)) return;
|
||||
var snapshot = await ProjectStorageService.LoadVersionAsync(SelectedProject.Id, SelectedVersionId);
|
||||
var options = await JS.InvokeAsync<ProjectDisplayOptions>("lmeMap.loadProjectSnapshot", snapshot, $"{SelectedProject.Name} - revisione");
|
||||
ApplyProjectDisplayOptions(options);
|
||||
ActiveTab = "map";
|
||||
}
|
||||
|
||||
private async Task CompareProjectVersion()
|
||||
{
|
||||
if (SelectedProject is null || string.IsNullOrWhiteSpace(SelectedVersionId)) return;
|
||||
var current = await ProjectStorageService.LoadAsync(SelectedProject.Id);
|
||||
var previous = await ProjectStorageService.LoadVersionAsync(SelectedProject.Id, SelectedVersionId);
|
||||
ProjectArchiveMessage = await JS.InvokeAsync<string>("lmeMap.compareProjectSnapshots", current, previous);
|
||||
}
|
||||
|
||||
private async Task ExportMapFile()
|
||||
@@ -1122,7 +1300,8 @@
|
||||
includeCadastral = ExportCadastral,
|
||||
includeDrawings = ExportDrawings,
|
||||
includePoi = ExportPoi,
|
||||
includeTrail = ExportTrail
|
||||
includeTrail = ExportTrail,
|
||||
selectedOnly = ExportSelectedOnly
|
||||
});
|
||||
var exported = await MapExportService.CreateAsync(ExportFileName, ExportFormat, geoJson);
|
||||
await Share.Default.RequestAsync(new ShareFileRequest
|
||||
@@ -1403,6 +1582,12 @@
|
||||
ExportDrawings = GetFlagPreference("export_drawings", true);
|
||||
ExportPoi = GetFlagPreference("export_poi", true);
|
||||
ExportTrail = GetFlagPreference("export_trail", true);
|
||||
ExportSelectedOnly = GetFlagPreference("export_selected_only", false);
|
||||
AutoSaveEnabled = GetFlagPreference("auto_save", true);
|
||||
SnapEnabled = GetFlagPreference("snap_enabled", true);
|
||||
SnapDistancePixels = Preferences.Default.Get($"{FlagPreferencePrefix}snap_distance", 14);
|
||||
GpsProximityEnabled = GetFlagPreference("gps_proximity", true);
|
||||
GpsBoundaryAlertEnabled = GetFlagPreference("gps_boundary_alert", false);
|
||||
|
||||
foreach (var layer in CadastralLayers)
|
||||
{
|
||||
@@ -1428,6 +1613,12 @@
|
||||
SetFlagPreference("export_drawings", ExportDrawings);
|
||||
SetFlagPreference("export_poi", ExportPoi);
|
||||
SetFlagPreference("export_trail", ExportTrail);
|
||||
SetFlagPreference("export_selected_only", ExportSelectedOnly);
|
||||
SetFlagPreference("auto_save", AutoSaveEnabled);
|
||||
SetFlagPreference("snap_enabled", SnapEnabled);
|
||||
Preferences.Default.Set($"{FlagPreferencePrefix}snap_distance", SnapDistancePixels);
|
||||
SetFlagPreference("gps_proximity", GpsProximityEnabled);
|
||||
SetFlagPreference("gps_boundary_alert", GpsBoundaryAlertEnabled);
|
||||
|
||||
foreach (var layer in CadastralLayers)
|
||||
{
|
||||
@@ -1453,6 +1644,19 @@
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ApplyAdvancedOptions()
|
||||
{
|
||||
SaveFlagPreferences();
|
||||
await JS.InvokeVoidAsync("lmeMap.setAdvancedOptions", new
|
||||
{
|
||||
autoSaveEnabled = AutoSaveEnabled,
|
||||
snapEnabled = SnapEnabled,
|
||||
snapDistancePixels = SnapDistancePixels,
|
||||
gpsProximityEnabled = GpsProximityEnabled,
|
||||
gpsBoundaryAlertEnabled = GpsBoundaryAlertEnabled
|
||||
});
|
||||
}
|
||||
|
||||
private static bool GetFlagPreference(string name, bool defaultValue) =>
|
||||
Preferences.Default.Get($"{FlagPreferencePrefix}{name}", defaultValue);
|
||||
|
||||
|
||||
@@ -28,8 +28,8 @@
|
||||
<ApplicationId>com.companyname.lmemappecatastaliapp</ApplicationId>
|
||||
|
||||
<!-- Versions -->
|
||||
<ApplicationDisplayVersion>0.2.29</ApplicationDisplayVersion>
|
||||
<ApplicationVersion>33</ApplicationVersion>
|
||||
<ApplicationDisplayVersion>0.3.0</ApplicationDisplayVersion>
|
||||
<ApplicationVersion>34</ApplicationVersion>
|
||||
|
||||
<!-- To develop, package, and publish an app to the Microsoft Store, see: https://aka.ms/MauiTemplateUnpackaged -->
|
||||
<WindowsPackageType>None</WindowsPackageType>
|
||||
|
||||
@@ -35,6 +35,8 @@ public sealed class MapExportService
|
||||
{
|
||||
"kml" => "kml",
|
||||
"kmz" => "kmz",
|
||||
"gpx" => "gpx",
|
||||
"pdf" => "pdf",
|
||||
_ => "geojson"
|
||||
};
|
||||
var baseName = NormalizeFileName(requestedName);
|
||||
@@ -49,6 +51,18 @@ public sealed class MapExportService
|
||||
return new(path, "application/geo+json", featureCount, Path.GetFileName(path));
|
||||
}
|
||||
|
||||
if (format == "gpx")
|
||||
{
|
||||
await File.WriteAllTextAsync(path, BuildGpx(features, baseName), new UTF8Encoding(false), cancellationToken);
|
||||
return new(path, "application/gpx+xml", featureCount, Path.GetFileName(path));
|
||||
}
|
||||
|
||||
if (format == "pdf")
|
||||
{
|
||||
await File.WriteAllBytesAsync(path, BuildPdfReport(features, baseName), cancellationToken);
|
||||
return new(path, "application/pdf", featureCount, Path.GetFileName(path));
|
||||
}
|
||||
|
||||
var kml = BuildKml(features, baseName);
|
||||
if (format == "kml")
|
||||
{
|
||||
@@ -67,6 +81,108 @@ public sealed class MapExportService
|
||||
return new(path, "application/vnd.google-earth.kmz", featureCount, Path.GetFileName(path));
|
||||
}
|
||||
|
||||
private static string BuildGpx(JsonElement features, string name)
|
||||
{
|
||||
var root = new XElement("gpx",
|
||||
new XAttribute("version", "1.1"),
|
||||
new XAttribute("creator", "LME Mappe Catastali 0.3.0"),
|
||||
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
|
||||
new XElement("metadata", new XElement("name", name)));
|
||||
foreach (var feature in features.EnumerateArray())
|
||||
{
|
||||
if (!feature.TryGetProperty("geometry", out var geometry) || geometry.ValueKind != JsonValueKind.Object) continue;
|
||||
var properties = feature.TryGetProperty("properties", out var value) ? value : default;
|
||||
var featureName = FeatureName(properties, GetString(properties, "_lmeCategory") ?? "drawing");
|
||||
var type = geometry.GetProperty("type").GetString();
|
||||
var coordinates = geometry.GetProperty("coordinates");
|
||||
if (type == "Point")
|
||||
{
|
||||
root.Add(GpxPoint("wpt", coordinates, featureName));
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var line in EnumerateGpxLines(type, coordinates))
|
||||
{
|
||||
root.Add(new XElement("trk", new XElement("name", featureName),
|
||||
new XElement("trkseg", line.Select(point => GpxPoint("trkpt", point, null)))));
|
||||
}
|
||||
}
|
||||
}
|
||||
return new XDocument(new XDeclaration("1.0", "utf-8", null), root).ToString();
|
||||
}
|
||||
|
||||
private static XElement GpxPoint(string element, JsonElement coordinate, string? name)
|
||||
{
|
||||
var values = coordinate.EnumerateArray().ToArray();
|
||||
var point = new XElement(element,
|
||||
new XAttribute("lat", values[1].GetDouble().ToString("G17", CultureInfo.InvariantCulture)),
|
||||
new XAttribute("lon", values[0].GetDouble().ToString("G17", CultureInfo.InvariantCulture)));
|
||||
if (!string.IsNullOrWhiteSpace(name)) point.Add(new XElement("name", name));
|
||||
return point;
|
||||
}
|
||||
|
||||
private static IEnumerable<JsonElement[]> EnumerateGpxLines(string? type, JsonElement coordinates)
|
||||
{
|
||||
if (type == "LineString") yield return coordinates.EnumerateArray().ToArray();
|
||||
else if (type == "Polygon")
|
||||
foreach (var ring in coordinates.EnumerateArray()) yield return ring.EnumerateArray().ToArray();
|
||||
else if (type == "MultiLineString")
|
||||
foreach (var line in coordinates.EnumerateArray()) yield return line.EnumerateArray().ToArray();
|
||||
else if (type == "MultiPolygon")
|
||||
foreach (var polygon in coordinates.EnumerateArray())
|
||||
foreach (var ring in polygon.EnumerateArray()) yield return ring.EnumerateArray().ToArray();
|
||||
}
|
||||
|
||||
private static byte[] BuildPdfReport(JsonElement features, string title)
|
||||
{
|
||||
var lines = new List<string>
|
||||
{
|
||||
title,
|
||||
$"Rapporto LME Mappe Catastali - {DateTime.Now:dd/MM/yyyy HH:mm}",
|
||||
$"Oggetti: {features.GetArrayLength()}",
|
||||
""
|
||||
};
|
||||
var index = 1;
|
||||
foreach (var feature in features.EnumerateArray())
|
||||
{
|
||||
var properties = feature.TryGetProperty("properties", out var value) ? value : default;
|
||||
var category = GetString(properties, "_lmeCategory") ?? "drawing";
|
||||
var geometry = feature.TryGetProperty("geometry", out var geo) ? geo.GetProperty("type").GetString() : "-";
|
||||
lines.Add($"{index++}. {FeatureName(properties, category)} [{category}, {geometry}]");
|
||||
}
|
||||
var content = new StringBuilder("BT /F1 16 Tf 48 790 Td ");
|
||||
foreach (var line in lines.Take(42))
|
||||
{
|
||||
var safe = line.Replace("\\", "\\\\").Replace("(", "\\(").Replace(")", "\\)")
|
||||
.Select(character => character <= 255 ? character : '?').ToArray();
|
||||
content.Append('(').Append(safe).Append(") Tj 0 -18 Td ");
|
||||
}
|
||||
content.Append("ET");
|
||||
var stream = Encoding.Latin1.GetBytes(content.ToString());
|
||||
var objects = new[]
|
||||
{
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
|
||||
$"<< /Length {stream.Length} >>\nstream\n{Encoding.Latin1.GetString(stream)}\nendstream",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"
|
||||
};
|
||||
using var output = new MemoryStream();
|
||||
using var writer = new StreamWriter(output, Encoding.Latin1, leaveOpen: true) { NewLine = "\n" };
|
||||
writer.Write("%PDF-1.4\n"); writer.Flush();
|
||||
var offsets = new List<long> { 0 };
|
||||
for (var i = 0; i < objects.Length; i++)
|
||||
{
|
||||
offsets.Add(output.Position); writer.Write($"{i + 1} 0 obj\n{objects[i]}\nendobj\n"); writer.Flush();
|
||||
}
|
||||
var xref = output.Position;
|
||||
writer.Write($"xref\n0 {objects.Length + 1}\n0000000000 65535 f \n");
|
||||
foreach (var offset in offsets.Skip(1)) writer.Write($"{offset:0000000000} 00000 n \n");
|
||||
writer.Write($"trailer << /Size {objects.Length + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF");
|
||||
writer.Flush();
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
private static string BuildKml(JsonElement features, string documentName)
|
||||
{
|
||||
var document = new XElement(Kml + "Document",
|
||||
@@ -97,6 +213,11 @@ public sealed class MapExportService
|
||||
var placemark = new XElement(Kml + "Placemark",
|
||||
new XElement(Kml + "name", FeatureName(properties, category)),
|
||||
new XElement(Kml + "styleUrl", $"#{NormalizeStyleId(category)}"));
|
||||
var featureStyle = BuildFeatureStyle(properties);
|
||||
if (featureStyle is not null)
|
||||
{
|
||||
placemark.Add(featureStyle);
|
||||
}
|
||||
|
||||
var extendedData = BuildExtendedData(properties);
|
||||
if (extendedData is not null)
|
||||
@@ -142,6 +263,37 @@ public sealed class MapExportService
|
||||
new XElement(Kml + "width", 3)),
|
||||
new XElement(Kml + "PolyStyle", new XElement(Kml + "color", fillColor)));
|
||||
|
||||
private static XElement? BuildFeatureStyle(JsonElement properties)
|
||||
{
|
||||
var color = GetString(properties, "_lmeColor");
|
||||
var fillColor = GetString(properties, "_lmeFillColor") ?? color;
|
||||
if (string.IsNullOrWhiteSpace(color) && string.IsNullOrWhiteSpace(fillColor)) return null;
|
||||
var weight = GetNumber(properties, "_lmeWeight", 3);
|
||||
var opacity = GetNumber(properties, "_lmeOpacity", 1);
|
||||
var fillOpacity = GetNumber(properties, "_lmeFillOpacity", 0.2);
|
||||
return new XElement(Kml + "Style",
|
||||
new XElement(Kml + "LineStyle",
|
||||
new XElement(Kml + "color", ToKmlColor(color ?? "#f97316", opacity)),
|
||||
new XElement(Kml + "width", weight.ToString("0.##", CultureInfo.InvariantCulture))),
|
||||
new XElement(Kml + "PolyStyle",
|
||||
new XElement(Kml + "color", ToKmlColor(fillColor ?? "#fb923c", fillOpacity))));
|
||||
}
|
||||
|
||||
private static double GetNumber(JsonElement properties, string name, double fallback) =>
|
||||
properties.ValueKind == JsonValueKind.Object
|
||||
&& properties.TryGetProperty(name, out var value)
|
||||
&& value.ValueKind == JsonValueKind.Number
|
||||
? value.GetDouble()
|
||||
: fallback;
|
||||
|
||||
private static string ToKmlColor(string html, double opacity)
|
||||
{
|
||||
var value = html.TrimStart('#');
|
||||
if (value.Length != 6) value = "f97316";
|
||||
var alpha = (int)Math.Round(Math.Clamp(opacity, 0, 1) * 255);
|
||||
return $"{alpha:x2}{value[4..6]}{value[2..4]}{value[0..2]}";
|
||||
}
|
||||
|
||||
private static XElement? BuildExtendedData(JsonElement properties)
|
||||
{
|
||||
if (properties.ValueKind != JsonValueKind.Object)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace LMEMappeCatastaliApp.Services;
|
||||
|
||||
@@ -13,8 +14,9 @@ public sealed class ProjectStorageService
|
||||
};
|
||||
|
||||
private string ProjectsDirectory => Path.Combine(FileSystem.AppDataDirectory, "Projects");
|
||||
private string HistoryDirectory => Path.Combine(ProjectsDirectory, ".history");
|
||||
|
||||
public async Task<IReadOnlyList<MapProjectSummary>> GetProjectsAsync()
|
||||
public async Task<IReadOnlyList<MapProjectSummary>> GetProjectsAsync(bool includeArchived = true)
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
@@ -22,6 +24,7 @@ public sealed class ProjectStorageService
|
||||
var files = await ReadProjectFilesAsync();
|
||||
return files
|
||||
.Select(item => item.Document.ToSummary())
|
||||
.Where(item => includeArchived || !item.IsArchived)
|
||||
.OrderByDescending(item => item.UpdatedAt)
|
||||
.ThenBy(item => item.Name, StringComparer.CurrentCultureIgnoreCase)
|
||||
.ToArray();
|
||||
@@ -56,14 +59,23 @@ public sealed class ProjectStorageService
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var id = existing?.Document.Id ?? Guid.NewGuid().ToString("N");
|
||||
if (existing is not null)
|
||||
{
|
||||
Directory.CreateDirectory(HistoryDirectory);
|
||||
var revisionName = $"{id}--{existing.Document.UpdatedAt:yyyyMMddHHmmssfff}{ProjectExtension}";
|
||||
File.Copy(existing.Path, Path.Combine(HistoryDirectory, revisionName), true);
|
||||
PruneHistory(id, 15);
|
||||
}
|
||||
var document = new MapProjectDocument
|
||||
{
|
||||
SchemaVersion = 1,
|
||||
SchemaVersion = 2,
|
||||
Id = id,
|
||||
Name = normalizedName,
|
||||
CreatedAt = existing?.Document.CreatedAt ?? now,
|
||||
UpdatedAt = now,
|
||||
IncludesCadastralParcels = includesCadastralParcels,
|
||||
Folder = existing?.Document.Folder ?? string.Empty,
|
||||
IsArchived = existing?.Document.IsArchived ?? false,
|
||||
Map = snapshotDocument.RootElement.Clone()
|
||||
};
|
||||
|
||||
@@ -93,6 +105,178 @@ public sealed class ProjectStorageService
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<MapProjectSummary> DuplicateAsync(string projectId)
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
var files = await ReadProjectFilesAsync();
|
||||
var source = files.FirstOrDefault(item => item.Document.Id == projectId)
|
||||
?? throw new FileNotFoundException("Il progetto selezionato non esiste piu'.");
|
||||
var usedNames = files.Select(item => item.Document.Name).ToHashSet(StringComparer.CurrentCultureIgnoreCase);
|
||||
var baseName = $"{source.Document.Name} - copia";
|
||||
var name = baseName;
|
||||
for (var index = 2; usedNames.Contains(name); index++)
|
||||
{
|
||||
name = $"{baseName} {index}";
|
||||
}
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var id = Guid.NewGuid().ToString("N");
|
||||
var copy = new MapProjectDocument
|
||||
{
|
||||
SchemaVersion = 2,
|
||||
Id = id,
|
||||
Name = name,
|
||||
CreatedAt = now,
|
||||
UpdatedAt = now,
|
||||
IncludesCadastralParcels = source.Document.IncludesCadastralParcels,
|
||||
Folder = source.Document.Folder,
|
||||
Map = source.Document.Map.Clone()
|
||||
};
|
||||
var path = Path.Combine(ProjectsDirectory, BuildFileName(name, id));
|
||||
await File.WriteAllTextAsync(path, JsonSerializer.Serialize(copy, _jsonOptions), new UTF8Encoding(false));
|
||||
return copy.ToSummary();
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task UpdateOrganizationAsync(string projectId, string? folder = null, bool? isArchived = null)
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
var project = (await ReadProjectFilesAsync()).FirstOrDefault(item => item.Document.Id == projectId)
|
||||
?? throw new FileNotFoundException("Il progetto selezionato non esiste piu'.");
|
||||
project.Document.Folder = NormalizeFolder(folder ?? project.Document.Folder);
|
||||
project.Document.IsArchived = isArchived ?? project.Document.IsArchived;
|
||||
project.Document.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
await File.WriteAllTextAsync(project.Path, JsonSerializer.Serialize(project.Document, _jsonOptions), new UTF8Encoding(false));
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<MapProjectVersion>> GetVersionsAsync(string projectId)
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(HistoryDirectory);
|
||||
var versions = new List<MapProjectVersion>();
|
||||
foreach (var path in Directory.EnumerateFiles(HistoryDirectory, $"{projectId}--*{ProjectExtension}"))
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var stream = File.OpenRead(path);
|
||||
var document = await JsonSerializer.DeserializeAsync<MapProjectDocument>(stream, _jsonOptions);
|
||||
if (document is not null)
|
||||
{
|
||||
versions.Add(new(Path.GetFileName(path), document.UpdatedAt));
|
||||
}
|
||||
}
|
||||
catch (JsonException) { }
|
||||
catch (IOException) { }
|
||||
}
|
||||
return versions.OrderByDescending(item => item.UpdatedAt).ToArray();
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task<string> LoadVersionAsync(string projectId, string versionId)
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (!versionId.StartsWith($"{projectId}--", StringComparison.Ordinal)
|
||||
|| Path.GetFileName(versionId) != versionId)
|
||||
{
|
||||
throw new InvalidDataException("Revisione non valida.");
|
||||
}
|
||||
var path = Path.Combine(HistoryDirectory, versionId);
|
||||
await using var stream = File.OpenRead(path);
|
||||
var document = await JsonSerializer.DeserializeAsync<MapProjectDocument>(stream, _jsonOptions)
|
||||
?? throw new InvalidDataException("Revisione non leggibile.");
|
||||
return document.Map.GetRawText();
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task<string> CreateBackupAsync()
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(ProjectsDirectory);
|
||||
var directory = Path.Combine(FileSystem.CacheDirectory, "Backups");
|
||||
Directory.CreateDirectory(directory);
|
||||
var path = Path.Combine(directory, $"LMEMappeCatastali-backup-{DateTime.Now:yyyyMMdd-HHmmss}.lmebackup.zip");
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
ZipFile.CreateFromDirectory(ProjectsDirectory, path, CompressionLevel.Optimal, false);
|
||||
return path;
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task<int> RestoreBackupAsync(string backupPath)
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(ProjectsDirectory);
|
||||
using var archive = ZipFile.OpenRead(backupPath);
|
||||
var restored = 0;
|
||||
foreach (var entry in archive.Entries.Where(item => item.FullName.EndsWith(ProjectExtension, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
var fileName = Path.GetFileName(entry.FullName);
|
||||
if (string.IsNullOrWhiteSpace(fileName)) continue;
|
||||
var targetDirectory = entry.FullName.Contains(".history/", StringComparison.OrdinalIgnoreCase)
|
||||
|| entry.FullName.Contains(".history\\", StringComparison.OrdinalIgnoreCase)
|
||||
? HistoryDirectory : ProjectsDirectory;
|
||||
Directory.CreateDirectory(targetDirectory);
|
||||
entry.ExtractToFile(Path.Combine(targetDirectory, fileName), true);
|
||||
if (targetDirectory == ProjectsDirectory) restored++;
|
||||
}
|
||||
return restored;
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task<string> CreateProjectPackageAsync(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'.");
|
||||
var directory = Path.Combine(FileSystem.CacheDirectory, "Projects");
|
||||
Directory.CreateDirectory(directory);
|
||||
var path = Path.Combine(directory, Path.GetFileName(project.Path));
|
||||
File.Copy(project.Path, path, true);
|
||||
return path;
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task<MapProjectSummary> ImportProjectAsync(string path)
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
await using var stream = File.OpenRead(path);
|
||||
var source = await JsonSerializer.DeserializeAsync<MapProjectDocument>(stream, _jsonOptions)
|
||||
?? throw new InvalidDataException("Progetto non leggibile.");
|
||||
if (source.Map.ValueKind != JsonValueKind.Object) throw new InvalidDataException("Mappa del progetto non valida.");
|
||||
source.Id = Guid.NewGuid().ToString("N");
|
||||
source.Name = NormalizeName(source.Name);
|
||||
source.CreatedAt = source.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
source.IsArchived = false;
|
||||
Directory.CreateDirectory(ProjectsDirectory);
|
||||
var target = Path.Combine(ProjectsDirectory, BuildFileName(source.Name, source.Id));
|
||||
await File.WriteAllTextAsync(target, JsonSerializer.Serialize(source, _jsonOptions), new UTF8Encoding(false));
|
||||
return source.ToSummary();
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task<string> LoadAsync(string projectId)
|
||||
{
|
||||
await _gate.WaitAsync();
|
||||
@@ -118,6 +302,13 @@ public sealed class ProjectStorageService
|
||||
.FirstOrDefault(item => item.Document.Id == projectId)
|
||||
?? throw new FileNotFoundException("Il progetto selezionato non esiste piu'.");
|
||||
File.Delete(project.Path);
|
||||
if (Directory.Exists(HistoryDirectory))
|
||||
{
|
||||
foreach (var path in Directory.EnumerateFiles(HistoryDirectory, $"{projectId}--*{ProjectExtension}"))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -179,19 +370,36 @@ public sealed class ProjectStorageService
|
||||
return $"{safeName}--{id[..8]}{ProjectExtension}";
|
||||
}
|
||||
|
||||
private void PruneHistory(string projectId, int keep)
|
||||
{
|
||||
foreach (var path in Directory.EnumerateFiles(HistoryDirectory, $"{projectId}--*{ProjectExtension}")
|
||||
.OrderByDescending(File.GetLastWriteTimeUtc).Skip(keep))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
|
||||
private static string NormalizeFolder(string value)
|
||||
{
|
||||
var normalized = string.Join(' ', (value ?? string.Empty).Split([' ', '\t', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries));
|
||||
return normalized[..Math.Min(normalized.Length, 60)];
|
||||
}
|
||||
|
||||
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 int SchemaVersion { get; set; }
|
||||
public string Id { get; set; } = string.Empty;
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
public DateTimeOffset UpdatedAt { get; set; }
|
||||
public bool IncludesCadastralParcels { get; set; }
|
||||
public string Folder { get; set; } = string.Empty;
|
||||
public bool IsArchived { get; set; }
|
||||
public JsonElement Map { get; set; }
|
||||
|
||||
public MapProjectSummary ToSummary() => new(Id, Name, UpdatedAt, IncludesCadastralParcels);
|
||||
public MapProjectSummary ToSummary() => new(Id, Name, UpdatedAt, IncludesCadastralParcels, Folder, IsArchived);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,4 +407,8 @@ public sealed record MapProjectSummary(
|
||||
string Id,
|
||||
string Name,
|
||||
DateTimeOffset UpdatedAt,
|
||||
bool IncludesCadastralParcels);
|
||||
bool IncludesCadastralParcels,
|
||||
string Folder,
|
||||
bool IsArchived);
|
||||
|
||||
public sealed record MapProjectVersion(string Id, DateTimeOffset UpdatedAt);
|
||||
+146
-1
@@ -177,7 +177,7 @@ input[type="checkbox"] {
|
||||
top: 72px;
|
||||
right: 12px;
|
||||
bottom: calc(var(--nav-height) + 8px);
|
||||
z-index: 940;
|
||||
z-index: 1080;
|
||||
display: grid;
|
||||
box-sizing: border-box;
|
||||
width: min(480px, 50vw);
|
||||
@@ -263,6 +263,151 @@ input[type="checkbox"] {
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.layer-selection-toolbar {
|
||||
position: sticky;
|
||||
top: -9px;
|
||||
z-index: 3;
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
padding: 8px 4px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: rgba(255, 255, 255, 0.98);
|
||||
}
|
||||
|
||||
.layer-selection-toolbar label,
|
||||
.layer-object-tools > label:not(.layer-manager-suboption),
|
||||
.layer-style-controls label {
|
||||
display: grid;
|
||||
gap: 3px;
|
||||
font-size: 9px;
|
||||
}
|
||||
|
||||
.layer-selection-summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 6px;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.layer-selection-summary button,
|
||||
.layer-batch-actions button,
|
||||
.layer-compact-actions button,
|
||||
.layer-object-tools > button {
|
||||
min-height: 28px;
|
||||
min-width: 0;
|
||||
padding: 4px 6px;
|
||||
font-size: 9px;
|
||||
}
|
||||
|
||||
.layer-selection-summary button {
|
||||
max-width: 48%;
|
||||
}
|
||||
|
||||
.layer-batch-actions,
|
||||
.layer-compact-actions {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.layer-group-tools,
|
||||
.layer-object-tools {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
padding: 7px;
|
||||
border: 1px dashed var(--layer-group-border, #cbd5da);
|
||||
border-radius: 4px;
|
||||
background: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
|
||||
.layer-group-tools {
|
||||
margin: 0 3px 4px;
|
||||
}
|
||||
|
||||
.layer-group-totals {
|
||||
color: var(--muted);
|
||||
font-size: 9px;
|
||||
}
|
||||
|
||||
.layer-style-controls {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.layer-style-controls input,
|
||||
.layer-style-controls select,
|
||||
.layer-object-tools textarea {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 28px;
|
||||
padding: 3px;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.layer-style-controls input[type="color"] {
|
||||
padding: 1px;
|
||||
}
|
||||
|
||||
.layer-photo-picker {
|
||||
position: relative;
|
||||
min-height: 32px;
|
||||
place-items: center;
|
||||
border: 1px dashed #8aa2aa;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.layer-photo-picker input {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.layer-photo-preview {
|
||||
display: block;
|
||||
width: 100%;
|
||||
max-height: 140px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.lme-popup-photo {
|
||||
display: block;
|
||||
width: min(240px, 60vw);
|
||||
max-height: 180px;
|
||||
margin-top: 6px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.lme-permanent-label {
|
||||
width: 0 !important;
|
||||
height: 0 !important;
|
||||
border: 0 !important;
|
||||
background: transparent !important;
|
||||
}
|
||||
|
||||
.lme-permanent-label span {
|
||||
position: absolute;
|
||||
transform: translate(-50%, -50%);
|
||||
padding: 2px 5px;
|
||||
border: 1px solid #52616c;
|
||||
border-radius: 3px;
|
||||
background: rgba(255, 255, 255, 0.92);
|
||||
color: #17212b;
|
||||
font-size: 10px;
|
||||
font-weight: 800;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.lme-offline-tile {
|
||||
box-sizing: border-box;
|
||||
width: 256px;
|
||||
height: 256px;
|
||||
border: 1px solid #d8e0e3;
|
||||
background-color: #f5f7f8;
|
||||
}
|
||||
|
||||
.layer-manager-group,
|
||||
.layer-manager-block,
|
||||
.layer-manager-object {
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
<script src="lib/googlemutant/Leaflet.GoogleMutant.js"></script>
|
||||
<script src="lib/jszip/jszip.min.js"></script>
|
||||
<script src="lib/togeojson/togeojson.umd.js"></script>
|
||||
<script src="lib/turf/turf.min.js"></script>
|
||||
<script src="js/lme-map.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
+582
-15
@@ -70,6 +70,18 @@ const lmeState = {
|
||||
managerObjectOrder: {},
|
||||
managerCategoryNames: {},
|
||||
managerExpandedRows: new Set(),
|
||||
managerSelectedObjectIds: new Set(),
|
||||
managerSearchText: "",
|
||||
permanentLabels: null,
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
historyBusy: false,
|
||||
snapEnabled: true,
|
||||
snapDistancePixels: 14,
|
||||
autoSaveEnabled: true,
|
||||
gpsProximityEnabled: true,
|
||||
gpsBoundaryAlertEnabled: false,
|
||||
lastBoundaryState: null,
|
||||
dotNetReference: null
|
||||
};
|
||||
|
||||
@@ -101,6 +113,11 @@ window.lmeMap = {
|
||||
startMeasurementDrawing,
|
||||
setDrawToolsVisible,
|
||||
clearDrawings,
|
||||
undoMapChange,
|
||||
redoMapChange,
|
||||
restoreAutosave,
|
||||
compareProjectSnapshots,
|
||||
setAdvancedOptions,
|
||||
createMapExportGeoJson,
|
||||
createProjectSnapshot,
|
||||
loadProjectSnapshot,
|
||||
@@ -119,6 +136,7 @@ window.lmeMap = {
|
||||
setNativeGpsPosition,
|
||||
setGpsPositionVisible,
|
||||
setGpsError,
|
||||
saveGpsMeasurementPoint,
|
||||
resize,
|
||||
showInfo: setInfo
|
||||
};
|
||||
@@ -173,6 +191,12 @@ function init(dotNetReference) {
|
||||
maxZoom: 22,
|
||||
attribution: "© OpenStreetMap contributors © CARTO"
|
||||
});
|
||||
lmeState.baseLayers.offline = L.gridLayer({ attribution: "Sfondo offline" });
|
||||
lmeState.baseLayers.offline.createTile = () => {
|
||||
const tile = document.createElement("div");
|
||||
tile.className = "lme-offline-tile";
|
||||
return tile;
|
||||
};
|
||||
|
||||
lmeState.currentBase = lmeState.baseLayers.satellite.addTo(lmeState.map);
|
||||
restoreLayerOrder();
|
||||
@@ -200,6 +224,7 @@ function init(dotNetReference) {
|
||||
opacity: 0.85
|
||||
}).addTo(lmeState.map);
|
||||
lmeState.managerHighlight = L.layerGroup().addTo(lmeState.map);
|
||||
lmeState.permanentLabels = L.layerGroup().addTo(lmeState.map);
|
||||
|
||||
refreshCadastreLayer();
|
||||
bindFileImport();
|
||||
@@ -558,6 +583,7 @@ function bindFileImport() {
|
||||
|
||||
try {
|
||||
const result = await readGisFile(file);
|
||||
rememberMapChange();
|
||||
const geojson = result.geojson;
|
||||
const parcelLayer = addImportedFeatures(geojson);
|
||||
const sheetGeojson = result.sheetGeojson || emptyFeatureCollection();
|
||||
@@ -577,6 +603,7 @@ function bindFileImport() {
|
||||
setInfo(`Caricato ${file.name}: ${featureCount} particelle/elementi${includedSheets}${ignored}${reprojected}.`);
|
||||
updateGpsInsideState();
|
||||
refreshLayerManager();
|
||||
finishMapChange();
|
||||
} catch (error) {
|
||||
setInfo(`File non leggibile: ${error.message}`);
|
||||
} finally {
|
||||
@@ -811,8 +838,14 @@ function kmlTextToGeoJson(text, sourceName) {
|
||||
const features = [];
|
||||
const visit = (node, folders) => {
|
||||
if (node?.type === "Feature") {
|
||||
const sourceProperties = node.properties || {};
|
||||
node.properties = {
|
||||
...(node.properties || {}),
|
||||
...sourceProperties,
|
||||
_lmeColor: sourceProperties._lmeColor || sourceProperties.stroke,
|
||||
_lmeFillColor: sourceProperties._lmeFillColor || sourceProperties.fill,
|
||||
_lmeWeight: sourceProperties._lmeWeight || sourceProperties["stroke-width"],
|
||||
_lmeOpacity: sourceProperties._lmeOpacity || sourceProperties["stroke-opacity"],
|
||||
_lmeFillOpacity: sourceProperties._lmeFillOpacity || sourceProperties["fill-opacity"],
|
||||
_lmeFolder: folders.filter(Boolean).join(" / "),
|
||||
_lmeSource: sourceName
|
||||
};
|
||||
@@ -1196,6 +1229,7 @@ function renameManagedObject(record, index) {
|
||||
setInfo("Nome non modificato: inserisci un testo.");
|
||||
return;
|
||||
}
|
||||
rememberMapChange();
|
||||
const properties = record.layer.feature.properties;
|
||||
properties.name = name;
|
||||
record.layer.lmeManagerLabel = record.categoryKey === "drawings" && record.layer instanceof L.Marker
|
||||
@@ -1204,7 +1238,9 @@ function renameManagedObject(record, index) {
|
||||
updateStoredFeaturePopup(record.layer);
|
||||
refreshImportedMeasurements();
|
||||
refreshDrawingMeasurements();
|
||||
refreshPermanentLabels();
|
||||
refreshLayerManager();
|
||||
finishMapChange();
|
||||
setInfo(`Oggetto rinominato: ${name}.`);
|
||||
}
|
||||
|
||||
@@ -1235,6 +1271,7 @@ function renameManagedCategory(category, records) {
|
||||
setInfo("Nome non modificato: inserisci un testo.");
|
||||
return;
|
||||
}
|
||||
rememberMapChange();
|
||||
lmeState.managerCategoryNames[category.key] = name;
|
||||
records.forEach(record => {
|
||||
if (record.layer?.feature?.properties) {
|
||||
@@ -1242,6 +1279,7 @@ function renameManagedCategory(category, records) {
|
||||
}
|
||||
});
|
||||
refreshLayerManager();
|
||||
finishMapChange();
|
||||
setInfo(`Gruppo rinominato: ${name}.`);
|
||||
}
|
||||
|
||||
@@ -1262,12 +1300,14 @@ function renameManagedBlock(category, source, records) {
|
||||
setInfo("Nome non modificato: inserisci un testo.");
|
||||
return;
|
||||
}
|
||||
rememberMapChange();
|
||||
records.forEach(record => {
|
||||
if (record.layer?.feature?.properties) {
|
||||
record.layer.feature.properties._lmeGroupName = name;
|
||||
}
|
||||
});
|
||||
refreshLayerManager();
|
||||
finishMapChange();
|
||||
setInfo(`Gruppo rinominato: ${name}.`);
|
||||
}
|
||||
|
||||
@@ -1322,12 +1362,17 @@ function removeManagedRecords(records, subject) {
|
||||
if (!records.length) {
|
||||
return;
|
||||
}
|
||||
if (records.some(record => record.layer?.feature?.properties?._lmeLocked)) {
|
||||
setInfo("Operazione annullata: sblocca prima tutti gli oggetti coinvolti.");
|
||||
return;
|
||||
}
|
||||
const message = records.length === 1
|
||||
? `Rimuovere ${subject} dal progetto? Non verra incluso nel prossimo salvataggio.`
|
||||
: `Rimuovere ${subject} e tutti i suoi ${records.length} oggetti dal progetto? Non verranno inclusi nel prossimo salvataggio.`;
|
||||
if (!window.confirm(message)) {
|
||||
return;
|
||||
}
|
||||
rememberMapChange();
|
||||
const removedIds = new Set(records.map(record => record.id));
|
||||
const categoryKeys = new Set(records.map(record => record.categoryKey));
|
||||
records.forEach(record => {
|
||||
@@ -1350,6 +1395,7 @@ function removeManagedRecords(records, subject) {
|
||||
refreshDrawingMeasurements();
|
||||
updateGpsInsideState();
|
||||
refreshLayerManager();
|
||||
finishMapChange();
|
||||
setInfo(`${records.length === 1 ? "Oggetto rimosso" : `${records.length} oggetti rimossi`} dal progetto.`);
|
||||
}
|
||||
|
||||
@@ -1401,6 +1447,7 @@ function refreshLayerManager() {
|
||||
applyStoredLayerManagerVisibility();
|
||||
container.innerHTML = "";
|
||||
lmeState.managerRecords = new Map();
|
||||
container.appendChild(renderLayerSelectionToolbar());
|
||||
const categoriesByKey = new Map(layerManagerCategories().map(category => [category.key, category]));
|
||||
lmeState.layerOrder.forEach(categoryKey => {
|
||||
const category = categoriesByKey.get(categoryKey);
|
||||
@@ -1418,7 +1465,13 @@ function refreshLayerManager() {
|
||||
records.sort((left, right) =>
|
||||
(positions.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (positions.get(right.id) ?? Number.MAX_SAFE_INTEGER));
|
||||
records.forEach(record => lmeState.managerRecords.set(record.id, record));
|
||||
container.appendChild(renderLayerManagerCategory(category, records));
|
||||
const rendered = renderLayerManagerCategory(category, records);
|
||||
const search = lmeState.managerSearchText.trim().toLocaleLowerCase("it");
|
||||
if (search && !records.some((record, index) => `${managedObjectLabel(record, index)} ${record.source}`.toLocaleLowerCase("it").includes(search))
|
||||
&& !managedCategoryName(category, records).toLocaleLowerCase("it").includes(search)) {
|
||||
rendered.hidden = true;
|
||||
}
|
||||
container.appendChild(rendered);
|
||||
});
|
||||
applyManagedVisualOrder(container);
|
||||
bindLayerManagerDrag(container);
|
||||
@@ -1469,6 +1522,7 @@ function renderLayerManagerCategory(category, records) {
|
||||
});
|
||||
bindManagedParentHighlight(group, `category:${category.key}`, records);
|
||||
const children = group.querySelector(".layer-manager-children");
|
||||
if (records.length) children.appendChild(renderManagedGroupTools(records));
|
||||
if (category.blocks) {
|
||||
const blocks = new Map();
|
||||
records.forEach(record => {
|
||||
@@ -1519,6 +1573,7 @@ function renderLayerManagerBlock(category, source, records) {
|
||||
});
|
||||
bindManagedParentHighlight(block, `block:${category.key}:${source}`, records);
|
||||
const children = block.querySelector(".layer-manager-children");
|
||||
children.appendChild(renderManagedGroupTools(records));
|
||||
records.forEach((record, index) => children.appendChild(renderLayerManagerObject(record, index)));
|
||||
return block;
|
||||
}
|
||||
@@ -1585,9 +1640,423 @@ function renderLayerManagerObject(record, index) {
|
||||
? rows.map(value => `<span>${escapeHtml(value)}</span>`).join("")
|
||||
: "<span>Nessuna misura disponibile</span>";
|
||||
details.appendChild(info);
|
||||
details.appendChild(renderManagedObjectTools(record));
|
||||
return object;
|
||||
}
|
||||
|
||||
function renderLayerSelectionToolbar() {
|
||||
const selectedCount = lmeState.managerSelectedObjectIds.size;
|
||||
const toolbar = document.createElement("section");
|
||||
toolbar.className = "layer-selection-toolbar";
|
||||
toolbar.innerHTML = `<label>Cerca oggetti<input type="search" value="${escapeHtml(lmeState.managerSearchText)}" placeholder="Nome o gruppo"></label>
|
||||
<div class="layer-selection-summary"><strong>${selectedCount} selezionati</strong><button type="button" data-action="clear">Deseleziona</button></div>
|
||||
<div class="layer-batch-actions">
|
||||
<button type="button" data-action="duplicate">Duplica</button><button type="button" data-action="move">Sposta</button>
|
||||
<button type="button" data-action="buffer">Buffer</button><button type="button" data-action="union">Unisci</button>
|
||||
<button type="button" data-action="split">Dividi</button><button type="button" data-action="delete" class="danger-command">Rimuovi</button>
|
||||
</div>`;
|
||||
const search = toolbar.querySelector("input");
|
||||
search.addEventListener("input", () => {
|
||||
lmeState.managerSearchText = search.value;
|
||||
refreshLayerManager();
|
||||
requestAnimationFrame(() => document.querySelector(".layer-selection-toolbar input")?.focus());
|
||||
});
|
||||
toolbar.querySelectorAll("button").forEach(button => button.addEventListener("click", () => {
|
||||
const records = [...lmeState.managerSelectedObjectIds]
|
||||
.map(id => lmeState.managerRecords?.get(id)).filter(Boolean);
|
||||
if (button.dataset.action === "clear") {
|
||||
lmeState.managerSelectedObjectIds.clear();
|
||||
refreshLayerManager();
|
||||
} else if (!records.length) {
|
||||
setInfo("Seleziona almeno un oggetto dalle sue opzioni.");
|
||||
} else if (button.dataset.action === "duplicate") duplicateManagedRecords(records);
|
||||
else if (button.dataset.action === "move") moveManagedRecords(records);
|
||||
else if (button.dataset.action === "buffer") bufferManagedRecords(records);
|
||||
else if (button.dataset.action === "union") unionManagedRecords(records);
|
||||
else if (button.dataset.action === "split") splitManagedRecords(records);
|
||||
else if (button.dataset.action === "delete") removeManagedRecords(records, "gli oggetti selezionati");
|
||||
}));
|
||||
return toolbar;
|
||||
}
|
||||
|
||||
function renderManagedGroupTools(records) {
|
||||
const tools = document.createElement("div");
|
||||
tools.className = "layer-group-tools";
|
||||
const properties = records[0]?.layer?.feature?.properties || {};
|
||||
tools.innerHTML = `<strong>Azioni gruppo</strong><span class="layer-group-totals">${escapeHtml(managedGroupTotals(records))}</span><div class="layer-style-controls">
|
||||
<label>Colore<input type="color" value="${normalizedColor(properties._lmeColor, "#16806a")}"></label>
|
||||
<label>Spessore<input type="range" min="1" max="10" step="1" value="${Number(properties._lmeWeight) || 3}"></label>
|
||||
<label>Opacita<input type="range" min="0.1" max="1" step="0.1" value="${Number(properties._lmeOpacity) || 1}"></label></div>
|
||||
<div class="layer-compact-actions"><button type="button" data-group-action="select">Seleziona tutti</button><button type="button" data-group-action="lock">Blocca/sblocca</button><button type="button" data-group-action="labels">Etichette</button></div>`;
|
||||
const inputs = tools.querySelectorAll("input");
|
||||
inputs.forEach(input => input.addEventListener("change", () => {
|
||||
applyManagedStyle(records, { color: inputs[0].value, weight: Number(inputs[1].value), opacity: Number(inputs[2].value) });
|
||||
}));
|
||||
tools.querySelector("[data-group-action='select']").addEventListener("click", () => {
|
||||
records.forEach(record => lmeState.managerSelectedObjectIds.add(record.id)); refreshLayerManager();
|
||||
});
|
||||
tools.querySelector("[data-group-action='lock']").addEventListener("click", () => {
|
||||
const lock = !records.every(record => Boolean(record.layer?.feature?.properties?._lmeLocked));
|
||||
updateManagedProperties(records, properties => { properties._lmeLocked = lock; });
|
||||
setInfo(lock ? "Gruppo bloccato." : "Gruppo sbloccato.");
|
||||
});
|
||||
tools.querySelector("[data-group-action='labels']").addEventListener("click", () => {
|
||||
const visible = !records.every(record => Boolean(record.layer?.feature?.properties?._lmeLabelVisible));
|
||||
updateManagedProperties(records, properties => { properties._lmeLabelVisible = visible; });
|
||||
});
|
||||
return tools;
|
||||
}
|
||||
|
||||
function managedGroupTotals(records) {
|
||||
let length = 0; let area = 0;
|
||||
records.forEach(record => {
|
||||
const layer = record.layer;
|
||||
if (layer instanceof L.Circle) { area += Math.PI * layer.getRadius() ** 2; length += 2 * Math.PI * layer.getRadius(); }
|
||||
else if (layer instanceof L.Polygon) polygonLatLngGroups(layer.getLatLngs()).forEach(polygon => {
|
||||
area += Math.abs(polygon.reduce((sum, ring, index) => sum + (index ? -1 : 1) * Math.abs(L.GeometryUtil.geodesicArea(ring)), 0));
|
||||
length += latLngPathLength(polygon[0] || [], true);
|
||||
});
|
||||
else if (layer instanceof L.Polyline) length += lineLatLngGroups(layer.getLatLngs()).reduce((sum, line) => sum + latLngPathLength(line, false), 0);
|
||||
});
|
||||
const values = []; if (area) values.push(`Area ${formatArea(area)}`); if (length) values.push(`Sviluppo ${formatDistance(length)}`);
|
||||
return values.join(" | ") || `${records.length} oggetti`;
|
||||
}
|
||||
|
||||
function renderManagedObjectTools(record) {
|
||||
const properties = record.layer.feature?.properties || (record.layer.feature = { type: "Feature", properties: {} }).properties;
|
||||
const selected = lmeState.managerSelectedObjectIds.has(record.id);
|
||||
const locked = Boolean(properties._lmeLocked);
|
||||
const tools = document.createElement("section");
|
||||
tools.className = "layer-object-tools";
|
||||
tools.innerHTML = `<label class="layer-manager-suboption"><input type="checkbox" data-field="selected" ${selected ? "checked" : ""}><span>Seleziona per azioni multiple</span></label>
|
||||
<label class="layer-manager-suboption"><input type="checkbox" data-field="locked" ${locked ? "checked" : ""}><span>Blocca modifiche e rimozione</span></label>
|
||||
<label class="layer-manager-suboption"><input type="checkbox" data-field="label" ${properties._lmeLabelVisible ? "checked" : ""}><span>Etichetta permanente sulla mappa</span></label>
|
||||
<div class="layer-style-controls"><label>Linea<input type="color" data-field="color" value="${normalizedColor(properties._lmeColor, "#f97316")}"></label>
|
||||
<label>Riempimento<input type="color" data-field="fillColor" value="${normalizedColor(properties._lmeFillColor, "#fb923c")}"></label>
|
||||
<label>Spessore<input type="range" data-field="weight" min="1" max="10" step="1" value="${Number(properties._lmeWeight) || 3}"></label>
|
||||
<label>Opacita<input type="range" data-field="opacity" min="0.1" max="1" step="0.1" value="${Number(properties._lmeOpacity) || 1}"></label>
|
||||
<label>Riempimento %<input type="range" data-field="fillOpacity" min="0" max="0.8" step="0.05" value="${Number.isFinite(Number(properties._lmeFillOpacity)) ? Number(properties._lmeFillOpacity) : 0.2}"></label>
|
||||
<label>Tratto<select data-field="dash"><option value="">Continuo</option><option value="8 6" ${properties._lmeDash === "8 6" ? "selected" : ""}>Tratteggiato</option><option value="2 6" ${properties._lmeDash === "2 6" ? "selected" : ""}>Puntinato</option></select></label></div>
|
||||
<label>Note<textarea data-field="notes" rows="2" maxlength="1000" placeholder="Note tecniche">${escapeHtml(properties._lmeNotes || "")}</textarea></label>
|
||||
<label class="layer-photo-picker">Foto<input type="file" data-field="photo" accept="image/*"></label>
|
||||
${properties._lmePhoto ? `<img class="layer-photo-preview" src="${properties._lmePhoto}" alt="Foto allegata"><button type="button" data-action="remove-photo">Rimuovi foto</button>` : ""}
|
||||
<div class="layer-compact-actions"><button type="button" data-action="duplicate">Duplica</button><button type="button" data-action="numeric">Coordinate</button><button type="button" data-action="move">Sposta</button><button type="button" data-action="buffer">Buffer</button></div>`;
|
||||
tools.querySelector("[data-field='selected']").addEventListener("change", event => {
|
||||
if (event.target.checked) lmeState.managerSelectedObjectIds.add(record.id);
|
||||
else lmeState.managerSelectedObjectIds.delete(record.id);
|
||||
refreshLayerManager();
|
||||
});
|
||||
tools.querySelector("[data-field='locked']").addEventListener("change", event => updateManagedProperties([record], value => { value._lmeLocked = event.target.checked; }));
|
||||
tools.querySelector("[data-field='label']").addEventListener("change", event => updateManagedProperties([record], value => { value._lmeLabelVisible = event.target.checked; }));
|
||||
tools.querySelectorAll(".layer-style-controls input,.layer-style-controls select").forEach(input => input.addEventListener("change", () => applyManagedStyle([record], {
|
||||
color: tools.querySelector("[data-field='color']").value,
|
||||
fillColor: tools.querySelector("[data-field='fillColor']").value,
|
||||
weight: Number(tools.querySelector("[data-field='weight']").value),
|
||||
opacity: Number(tools.querySelector("[data-field='opacity']").value),
|
||||
fillOpacity: Number(tools.querySelector("[data-field='fillOpacity']").value),
|
||||
dash: tools.querySelector("[data-field='dash']").value
|
||||
})));
|
||||
tools.querySelector("[data-field='notes']").addEventListener("change", event => updateManagedProperties([record], value => { value._lmeNotes = event.target.value.trim(); }));
|
||||
tools.querySelector("[data-field='photo']").addEventListener("change", async event => {
|
||||
const file = event.target.files?.[0]; if (!file) return;
|
||||
if (file.size > 2_500_000) { setInfo("Foto troppo grande: usa un file inferiore a 2,5 MB."); return; }
|
||||
const dataUrl = await fileToDataUrl(file);
|
||||
updateManagedProperties([record], value => { value._lmePhoto = dataUrl; });
|
||||
});
|
||||
tools.querySelector("[data-action='remove-photo']")?.addEventListener("click", () => updateManagedProperties([record], value => { delete value._lmePhoto; }));
|
||||
tools.querySelector("[data-action='duplicate']").addEventListener("click", () => duplicateManagedRecords([record]));
|
||||
tools.querySelector("[data-action='numeric']").addEventListener("click", () => numericEditManagedRecord(record));
|
||||
tools.querySelector("[data-action='move']").addEventListener("click", () => moveManagedRecords([record]));
|
||||
tools.querySelector("[data-action='buffer']").addEventListener("click", () => bufferManagedRecords([record]));
|
||||
return tools;
|
||||
}
|
||||
|
||||
function normalizedColor(value, fallback) {
|
||||
return /^#[0-9a-f]{6}$/i.test(String(value || "")) ? value : fallback;
|
||||
}
|
||||
|
||||
function updateManagedProperties(records, change) {
|
||||
rememberMapChange();
|
||||
records.forEach(record => {
|
||||
record.layer.feature ||= { type: "Feature", properties: {} };
|
||||
record.layer.feature.properties ||= {};
|
||||
change(record.layer.feature.properties);
|
||||
applyStyleFromProperties(record.layer);
|
||||
updateStoredFeaturePopup(record.layer);
|
||||
});
|
||||
refreshPermanentLabels();
|
||||
refreshLayerManager();
|
||||
finishMapChange();
|
||||
}
|
||||
|
||||
function applyManagedStyle(records, style) {
|
||||
updateManagedProperties(records, properties => {
|
||||
properties._lmeColor = style.color;
|
||||
properties._lmeFillColor = style.fillColor || style.color;
|
||||
properties._lmeWeight = style.weight;
|
||||
properties._lmeOpacity = style.opacity;
|
||||
if (style.fillOpacity !== undefined) properties._lmeFillOpacity = style.fillOpacity;
|
||||
if (style.dash !== undefined) properties._lmeDash = style.dash;
|
||||
});
|
||||
}
|
||||
|
||||
function applyStyleFromProperties(layer) {
|
||||
const properties = layer?.feature?.properties || {};
|
||||
if (typeof layer?.setStyle === "function") {
|
||||
layer.setStyle({
|
||||
color: properties._lmeColor || layer.options.color,
|
||||
fillColor: properties._lmeFillColor || layer.options.fillColor,
|
||||
weight: Number(properties._lmeWeight) || layer.options.weight,
|
||||
opacity: Number.isFinite(Number(properties._lmeOpacity)) ? Number(properties._lmeOpacity) : layer.options.opacity,
|
||||
fillOpacity: Number.isFinite(Number(properties._lmeFillOpacity)) ? Number(properties._lmeFillOpacity) : layer.options.fillOpacity,
|
||||
dashArray: properties._lmeDash || null
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function refreshPermanentLabels() {
|
||||
lmeState.permanentLabels?.clearLayers();
|
||||
layerManagerCategories().forEach(category => managedRecordsForCategory(category).forEach((record, index) => {
|
||||
const properties = record.layer?.feature?.properties || {};
|
||||
if (!properties._lmeLabelVisible || lmeState.managerHiddenObjectIds.has(record.id)) return;
|
||||
const center = layerLabelPosition(record.layer); if (!center) return;
|
||||
L.marker(center, { pane: "tooltipPane", interactive: false, icon: L.divIcon({ className: "lme-permanent-label", html: `<span>${escapeHtml(managedObjectLabel(record, index))}</span>`, iconSize: null }) }).addTo(lmeState.permanentLabels);
|
||||
}));
|
||||
}
|
||||
|
||||
function layerLabelPosition(layer) {
|
||||
if (typeof layer?.getBounds === "function" && layer.getBounds().isValid()) return layer.getBounds().getCenter();
|
||||
if (typeof layer?.getLatLng === "function") return layer.getLatLng();
|
||||
return null;
|
||||
}
|
||||
|
||||
function fileToDataUrl(file) {
|
||||
return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(file); });
|
||||
}
|
||||
|
||||
function addDrawingFeature(feature, select = false) {
|
||||
let added = null;
|
||||
L.geoJSON(feature, {
|
||||
pane: "drawingsPane",
|
||||
style: storedFeatureStyle,
|
||||
pointToLayer: (item, latlng) => item?.properties?._lmeShape === "circle" && Number(item.properties._lmeRadius) > 0
|
||||
? L.circle(latlng, { pane: "drawingsPane", renderer: lmeState.drawingsRenderer, radius: Number(item.properties._lmeRadius) })
|
||||
: L.marker(latlng, { pane: "drawingsPane", draggable: false }),
|
||||
onEachFeature: (item, layer) => {
|
||||
annotateDrawingLayer(layer, item?.properties?._lmeShape);
|
||||
applyStyleFromProperties(layer);
|
||||
updateStoredFeaturePopup(layer);
|
||||
lmeState.drawings.addLayer(layer);
|
||||
added = layer;
|
||||
}
|
||||
});
|
||||
if (select && added) selectDrawingLayer(added);
|
||||
return added;
|
||||
}
|
||||
|
||||
function storedFeatureStyle(feature) {
|
||||
const properties = feature?.properties || {};
|
||||
return {
|
||||
renderer: lmeState.drawingsRenderer,
|
||||
color: properties._lmeColor || "#f97316",
|
||||
fillColor: properties._lmeFillColor || "#fb923c",
|
||||
weight: Number(properties._lmeWeight) || 3,
|
||||
opacity: Number.isFinite(Number(properties._lmeOpacity)) ? Number(properties._lmeOpacity) : 1,
|
||||
fillOpacity: Number.isFinite(Number(properties._lmeFillOpacity)) ? Number(properties._lmeFillOpacity) : 0.2,
|
||||
dashArray: properties._lmeDash || null
|
||||
};
|
||||
}
|
||||
|
||||
function duplicateManagedRecords(records) {
|
||||
if (records.some(record => record.layer?.feature?.properties?._lmeLocked)) { setInfo("Sblocca gli oggetti da duplicare."); return; }
|
||||
rememberMapChange();
|
||||
records.forEach((record, index) => {
|
||||
const feature = record.layer.toGeoJSON();
|
||||
feature.properties = { ...(feature.properties || {}), name: `${managedObjectLabel(record, index)} - copia`, _lmeManagerId: undefined };
|
||||
if (record.layer instanceof L.Circle) {
|
||||
const point = turf.transformTranslate(feature, 1.5, 45, { units: "meters" });
|
||||
point.properties._lmeShape = "circle";
|
||||
point.properties._lmeRadius = record.layer.getRadius();
|
||||
addDrawingFeature(point);
|
||||
} else {
|
||||
addDrawingFeature(turf.transformTranslate(feature, 1.5, 45, { units: "meters" }));
|
||||
}
|
||||
});
|
||||
refreshDrawingMeasurements(); refreshLayerManager(); finishMapChange();
|
||||
setInfo(`${records.length} ${records.length === 1 ? "oggetto duplicato" : "oggetti duplicati"}.`);
|
||||
}
|
||||
|
||||
function moveManagedRecords(records) {
|
||||
if (records.some(record => record.layer?.feature?.properties?._lmeLocked)) { setInfo("Sblocca gli oggetti da spostare."); return; }
|
||||
const north = Number(window.prompt("Spostamento verso nord in metri (negativo verso sud)", "0"));
|
||||
if (!Number.isFinite(north)) return;
|
||||
const east = Number(window.prompt("Spostamento verso est in metri (negativo verso ovest)", "0"));
|
||||
if (!Number.isFinite(east) || (!north && !east)) return;
|
||||
const distance = Math.hypot(north, east);
|
||||
const bearing = Math.atan2(east, north) * 180 / Math.PI;
|
||||
rememberMapChange();
|
||||
records.forEach(record => {
|
||||
const moved = turf.transformTranslate(record.layer.toGeoJSON(), distance, bearing, { units: "meters" });
|
||||
replaceManagedLayer(record, moved);
|
||||
});
|
||||
finishManagedGeometryChange(`Spostati ${records.length} oggetti.`);
|
||||
}
|
||||
|
||||
function bufferManagedRecords(records) {
|
||||
const meters = Number(window.prompt("Distanza buffer in metri", "5"));
|
||||
if (!Number.isFinite(meters) || meters <= 0) return;
|
||||
rememberMapChange();
|
||||
let count = 0;
|
||||
records.forEach((record, index) => {
|
||||
const buffered = turf.buffer(record.layer.toGeoJSON(), meters, { units: "meters" });
|
||||
if (!buffered) return;
|
||||
buffered.properties = { ...(record.layer.feature?.properties || {}), name: `Buffer ${meters} m - ${managedObjectLabel(record, index)}`, _lmeShape: "polygon", _lmeManagerId: undefined };
|
||||
addDrawingFeature(buffered); count++;
|
||||
});
|
||||
finishManagedGeometryChange(`Creati ${count} buffer da ${formatDistance(meters)}.`);
|
||||
}
|
||||
|
||||
function unionManagedRecords(records) {
|
||||
const polygons = records.filter(record => record.layer instanceof L.Polygon).map(record => record.layer.toGeoJSON());
|
||||
if (polygons.length < 2) { setInfo("Per unire seleziona almeno due aree o poligoni."); return; }
|
||||
try {
|
||||
const merged = turf.union(turf.featureCollection(polygons));
|
||||
if (!merged) throw new Error("le aree non producono un risultato");
|
||||
rememberMapChange();
|
||||
merged.properties = { ...(polygons[0].properties || {}), name: "Unione aree", _lmeShape: "polygon", _lmeManagerId: undefined };
|
||||
addDrawingFeature(merged, true);
|
||||
polygons.forEach((_feature, index) => removeRecordWithoutPrompt(records.filter(record => record.layer instanceof L.Polygon)[index]));
|
||||
lmeState.managerSelectedObjectIds.clear();
|
||||
finishManagedGeometryChange("Aree unite in un nuovo oggetto.");
|
||||
} catch (error) { setInfo(`Unione non riuscita: ${error.message}`); }
|
||||
}
|
||||
|
||||
function splitManagedRecords(records) {
|
||||
const polygonRecord = records.find(record => record.layer instanceof L.Polygon);
|
||||
const lineRecord = records.find(record => record.layer instanceof L.Polyline && !(record.layer instanceof L.Polygon));
|
||||
if (!polygonRecord || !lineRecord) { setInfo("Per dividere seleziona un poligono e una linea di taglio."); return; }
|
||||
try {
|
||||
const cutter = turf.buffer(lineRecord.layer.toGeoJSON(), 0.02, { units: "meters" });
|
||||
const split = turf.difference(turf.featureCollection([polygonRecord.layer.toGeoJSON(), cutter]));
|
||||
const parts = split ? turf.flatten(split).features : [];
|
||||
if (parts.length < 2) throw new Error("la linea deve attraversare completamente il poligono");
|
||||
rememberMapChange();
|
||||
parts.forEach((part, index) => {
|
||||
part.properties = { ...(polygonRecord.layer.feature?.properties || {}), name: `${managedObjectLabel(polygonRecord, 0)} - parte ${index + 1}`, _lmeManagerId: undefined };
|
||||
addDrawingFeature(part);
|
||||
});
|
||||
removeRecordWithoutPrompt(polygonRecord);
|
||||
lmeState.managerSelectedObjectIds.clear();
|
||||
finishManagedGeometryChange(`Poligono diviso in ${parts.length} parti.`);
|
||||
} catch (error) { setInfo(`Divisione non riuscita: ${error.message}`); }
|
||||
}
|
||||
|
||||
function numericEditManagedRecord(record) {
|
||||
if (record.layer?.feature?.properties?._lmeLocked) { setInfo("Sblocca prima l'oggetto."); return; }
|
||||
if (record.layer instanceof L.Circle) {
|
||||
const center = record.layer.getLatLng();
|
||||
const value = window.prompt("Latitudine, longitudine, raggio in metri", `${center.lat.toFixed(7)}, ${center.lng.toFixed(7)}, ${record.layer.getRadius().toFixed(2)}`);
|
||||
if (value === null) return;
|
||||
const parts = value.split(/[;, ]+/).map(Number).filter(Number.isFinite);
|
||||
if (parts.length < 3) { setInfo("Inserisci latitudine, longitudine e raggio validi."); return; }
|
||||
rememberMapChange(); record.layer.setLatLng([parts[0], parts[1]]); record.layer.setRadius(parts[2]); annotateDrawingLayer(record.layer, "circle");
|
||||
} else if (typeof record.layer?.getLatLng === "function") {
|
||||
const point = record.layer.getLatLng();
|
||||
const value = window.prompt("Latitudine, longitudine", `${point.lat.toFixed(7)}, ${point.lng.toFixed(7)}`);
|
||||
if (value === null) return;
|
||||
const parts = value.split(/[;, ]+/).map(Number).filter(Number.isFinite);
|
||||
if (parts.length < 2) { setInfo("Inserisci coordinate valide."); return; }
|
||||
rememberMapChange(); record.layer.setLatLng([parts[0], parts[1]]);
|
||||
} else {
|
||||
const lines = lineLatLngGroups(record.layer.getLatLngs());
|
||||
const current = lines[0]?.map(point => `${point.lat.toFixed(7)},${point.lng.toFixed(7)}`).join("; ") || "";
|
||||
const value = window.prompt("Vertici: coppie latitudine,longitudine separate da punto e virgola", current);
|
||||
if (value === null) return;
|
||||
const points = value.split(";").map(pair => pair.split(",").map(Number)).filter(pair => pair.length === 2 && pair.every(Number.isFinite));
|
||||
if (points.length < 2) { setInfo("Servono almeno due vertici validi."); return; }
|
||||
rememberMapChange(); record.layer.setLatLngs(points.map(point => L.latLng(point[0], point[1])));
|
||||
}
|
||||
finishManagedGeometryChange("Coordinate aggiornate.");
|
||||
}
|
||||
|
||||
function replaceManagedLayer(record, feature) {
|
||||
const parent = record.parent?.hasLayer?.(record.layer) ? record.parent : lmeState.drawings;
|
||||
parent.removeLayer?.(record.layer);
|
||||
clearManagedObjectState(record.id);
|
||||
feature.properties = { ...(record.layer.feature?.properties || {}), ...(feature.properties || {}), _lmeManagerId: undefined };
|
||||
addDrawingFeature(feature);
|
||||
}
|
||||
|
||||
function removeRecordWithoutPrompt(record) {
|
||||
record.parent?.removeLayer?.(record.layer); clearManagedObjectState(record.id);
|
||||
}
|
||||
|
||||
function finishManagedGeometryChange(message) {
|
||||
refreshImportedMeasurements(); refreshDrawingMeasurements(); refreshPermanentLabels(); updateGpsInsideState(); refreshLayerManager(); finishMapChange(); setInfo(message);
|
||||
}
|
||||
|
||||
function rememberMapChange() {
|
||||
if (lmeState.historyBusy || !lmeState.map) return;
|
||||
const snapshot = createProjectSnapshot(true);
|
||||
if (lmeState.undoStack.at(-1) !== snapshot) lmeState.undoStack.push(snapshot);
|
||||
if (lmeState.undoStack.length > 30) lmeState.undoStack.shift();
|
||||
lmeState.redoStack = [];
|
||||
}
|
||||
|
||||
function finishMapChange() {
|
||||
if (!lmeState.autoSaveEnabled || lmeState.historyBusy || !lmeState.map) return;
|
||||
try { localStorage.setItem("lmeAutosaveV3", createProjectSnapshot(true)); } catch { }
|
||||
}
|
||||
|
||||
function undoMapChange() {
|
||||
if (!lmeState.undoStack.length) { setInfo("Nessuna operazione da annullare."); return; }
|
||||
lmeState.redoStack.push(createProjectSnapshot(true));
|
||||
restoreHistorySnapshot(lmeState.undoStack.pop(), "Operazione annullata.");
|
||||
}
|
||||
|
||||
function redoMapChange() {
|
||||
if (!lmeState.redoStack.length) { setInfo("Nessuna operazione da ripristinare."); return; }
|
||||
lmeState.undoStack.push(createProjectSnapshot(true));
|
||||
restoreHistorySnapshot(lmeState.redoStack.pop(), "Operazione ripristinata.");
|
||||
}
|
||||
|
||||
function restoreHistorySnapshot(snapshot, message) {
|
||||
lmeState.historyBusy = true;
|
||||
try { loadProjectSnapshot(snapshot, "cronologia"); setInfo(message); } finally { lmeState.historyBusy = false; }
|
||||
}
|
||||
|
||||
function restoreAutosave() {
|
||||
const snapshot = localStorage.getItem("lmeAutosaveV3");
|
||||
if (!snapshot) { setInfo("Nessun recupero automatico disponibile."); return false; }
|
||||
rememberMapChange(); loadProjectSnapshot(snapshot, "recupero automatico"); return true;
|
||||
}
|
||||
|
||||
function setAdvancedOptions(options) {
|
||||
const value = options || {};
|
||||
lmeState.snapEnabled = value.snapEnabled !== false;
|
||||
lmeState.snapDistancePixels = Math.max(4, Math.min(40, Number(value.snapDistancePixels) || 14));
|
||||
lmeState.autoSaveEnabled = value.autoSaveEnabled !== false;
|
||||
lmeState.gpsProximityEnabled = value.gpsProximityEnabled !== false;
|
||||
lmeState.gpsBoundaryAlertEnabled = Boolean(value.gpsBoundaryAlertEnabled);
|
||||
}
|
||||
|
||||
function compareProjectSnapshots(currentRaw, previousRaw) {
|
||||
const current = typeof currentRaw === "string" ? JSON.parse(currentRaw) : currentRaw;
|
||||
const previous = typeof previousRaw === "string" ? JSON.parse(previousRaw) : previousRaw;
|
||||
const collect = snapshot => ["drawings", "imported", "importedSheets", "selectedParcels"]
|
||||
.flatMap(key => snapshot?.[key]?.features || []);
|
||||
const keyFor = (feature, index) => feature?.properties?._lmeManagerId
|
||||
|| `${feature?.properties?.name || feature?.properties?.Name || "object"}:${index}`;
|
||||
const currentMap = new Map(collect(current).map((feature, index) => [keyFor(feature, index), JSON.stringify(feature)]));
|
||||
const previousMap = new Map(collect(previous).map((feature, index) => [keyFor(feature, index), JSON.stringify(feature)]));
|
||||
let added = 0; let removed = 0; let changed = 0;
|
||||
currentMap.forEach((value, key) => { if (!previousMap.has(key)) added++; else if (previousMap.get(key) !== value) changed++; });
|
||||
previousMap.forEach((_value, key) => { if (!currentMap.has(key)) removed++; });
|
||||
const message = `Confronto revisione: ${added} aggiunti, ${removed} rimossi, ${changed} modificati.`;
|
||||
setInfo(message);
|
||||
return message;
|
||||
}
|
||||
|
||||
function renderLayerManagerVisibilityOption(label, checked, onChange) {
|
||||
const option = document.createElement("label");
|
||||
option.className = "layer-manager-suboption";
|
||||
@@ -1753,6 +2222,7 @@ function setManagedObjectVisible(record, visible, refresh = true) {
|
||||
saveLayerManagerState();
|
||||
refreshImportedMeasurements();
|
||||
refreshDrawingMeasurements();
|
||||
refreshPermanentLabels();
|
||||
if (refresh) {
|
||||
refreshLayerManager();
|
||||
}
|
||||
@@ -2127,7 +2597,7 @@ function addImportedFeatures(geojson) {
|
||||
fillColor: "#ffffff",
|
||||
fillOpacity: 0.9
|
||||
}),
|
||||
onEachFeature: bindStoredFeaturePopup
|
||||
onEachFeature: (feature, layer) => { bindStoredFeaturePopup(feature, layer); applyStyleFromProperties(layer); }
|
||||
}).addTo(lmeState.imported);
|
||||
layer.lmeManagerLabel = managedGeoJsonLabel(geojson, "Dati importati");
|
||||
return layer;
|
||||
@@ -2144,7 +2614,7 @@ function addImportedSheetFeatures(geojson) {
|
||||
fillColor: "#ffffff",
|
||||
fillOpacity: 0.85
|
||||
}),
|
||||
onEachFeature: bindStoredFeaturePopup
|
||||
onEachFeature: (feature, layer) => { bindStoredFeaturePopup(feature, layer); applyStyleFromProperties(layer); }
|
||||
}).addTo(lmeState.importedSheets);
|
||||
layer.lmeManagerLabel = managedGeoJsonLabel(geojson, "Cornice o foglio");
|
||||
return layer;
|
||||
@@ -2193,6 +2663,7 @@ function fitImported() {
|
||||
}
|
||||
|
||||
function clearImported() {
|
||||
rememberMapChange();
|
||||
clearManagedCategoryState("imported");
|
||||
clearManagedCategoryState("importedSheets");
|
||||
lmeState.imported.clearLayers();
|
||||
@@ -2203,9 +2674,11 @@ function clearImported() {
|
||||
setInfo("File GIS rimossi.");
|
||||
updateGpsInsideState();
|
||||
refreshLayerManager();
|
||||
finishMapChange();
|
||||
}
|
||||
|
||||
function addProjectMarker(name) {
|
||||
rememberMapChange();
|
||||
const center = lmeState.map.getCenter();
|
||||
const label = (name || "Nuovo POI").trim();
|
||||
const marker = L.marker(center, { pane: "drawingsPane", draggable: false }).addTo(lmeState.drawings);
|
||||
@@ -2219,6 +2692,7 @@ function addProjectMarker(name) {
|
||||
refreshDrawingMeasurements();
|
||||
refreshLayerManager();
|
||||
selectDrawingLayer(marker);
|
||||
finishMapChange();
|
||||
}
|
||||
|
||||
function configureDrawLabels() {
|
||||
@@ -2243,6 +2717,7 @@ function bindDrawingEvents() {
|
||||
return;
|
||||
}
|
||||
lmeState.map.on(L.Draw.Event.CREATED, event => {
|
||||
snapDrawingLayer(event.layer);
|
||||
annotateDrawingLayer(event.layer, event.layerType);
|
||||
lmeState.drawings.addLayer(event.layer);
|
||||
refreshDrawingMeasurements();
|
||||
@@ -2257,12 +2732,16 @@ function bindDrawingEvents() {
|
||||
setInfo(completedLabels[event.layerType] || "Disegno completato.");
|
||||
refreshLayerManager();
|
||||
selectDrawingLayer(event.layer);
|
||||
finishMapChange();
|
||||
});
|
||||
lmeState.map.on(L.Draw.Event.DRAWSTART, rememberMapChange);
|
||||
lmeState.map.on(L.Draw.Event.EDITSTART, rememberMapChange);
|
||||
lmeState.map.on(L.Draw.Event.EDITED, event => {
|
||||
event.layers.eachLayer(layer => annotateDrawingLayer(layer));
|
||||
event.layers.eachLayer(layer => { snapDrawingLayer(layer); annotateDrawingLayer(layer); });
|
||||
refreshDrawingMeasurements();
|
||||
updateGpsInsideState();
|
||||
refreshLayerManager();
|
||||
finishMapChange();
|
||||
});
|
||||
lmeState.map.on(L.Draw.Event.DELETED, event => {
|
||||
event.layers?.eachLayer(layer => lmeState.drawings.removeLayer(layer));
|
||||
@@ -2270,6 +2749,7 @@ function bindDrawingEvents() {
|
||||
refreshDrawingMeasurements();
|
||||
updateGpsInsideState();
|
||||
refreshLayerManager();
|
||||
finishMapChange();
|
||||
});
|
||||
lmeState.map.on(L.Draw.Event.DRAWSTOP, () => {
|
||||
lmeState.activeDrawHandler = null;
|
||||
@@ -2425,6 +2905,9 @@ function startScopedDrawingEdit(targetGroup, scope) {
|
||||
if (!mode?.handler) {
|
||||
return;
|
||||
}
|
||||
const locked = targetGroup.getLayers().filter(layer => layer?.feature?.properties?._lmeLocked);
|
||||
if (locked.length) { setInfo("Sblocca gli oggetti prima di modificarli."); return; }
|
||||
rememberMapChange();
|
||||
mode.handler._featureGroup = targetGroup;
|
||||
mode.handler.options.featureGroup = targetGroup;
|
||||
mode.handler.enable();
|
||||
@@ -2443,6 +2926,7 @@ function removeSelectedDrawing() {
|
||||
setInfo("Salva o annulla la modifica prima di eliminare il disegno.");
|
||||
return;
|
||||
}
|
||||
if (layer.feature?.properties?._lmeLocked) { setInfo("Sblocca prima l'oggetto selezionato."); return; }
|
||||
const record = {
|
||||
id: managedLayerId(layer, "drawings"),
|
||||
categoryKey: "drawings",
|
||||
@@ -2453,6 +2937,7 @@ function removeSelectedDrawing() {
|
||||
if (!window.confirm(`Eliminare solo '${name}' dal progetto?`)) {
|
||||
return;
|
||||
}
|
||||
rememberMapChange();
|
||||
lmeState.drawingSelection.clearLayers();
|
||||
lmeState.drawings.removeLayer(layer);
|
||||
clearManagedObjectState(record.id);
|
||||
@@ -2460,6 +2945,7 @@ function removeSelectedDrawing() {
|
||||
refreshDrawingMeasurements();
|
||||
updateGpsInsideState();
|
||||
refreshLayerManager();
|
||||
finishMapChange();
|
||||
setInfo(`'${name}' eliminato dal progetto.`);
|
||||
}
|
||||
|
||||
@@ -2598,6 +3084,10 @@ function clearDrawings() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (managedRecordsForCategory(layerManagerCategories().find(item => item.key === "drawings")).some(record => record.layer?.feature?.properties?._lmeLocked)) {
|
||||
setInfo("Sblocca tutti i disegni prima di eliminarli."); return;
|
||||
}
|
||||
rememberMapChange();
|
||||
drawingEditToolbar()?.disable?.();
|
||||
lmeState.drawingSelection?.clearLayers();
|
||||
clearManagerHighlight();
|
||||
@@ -2607,6 +3097,25 @@ function clearDrawings() {
|
||||
updateGpsInsideState();
|
||||
setInfo("Disegni e POI eliminati dalla mappa.");
|
||||
refreshLayerManager();
|
||||
finishMapChange();
|
||||
}
|
||||
|
||||
function snapDrawingLayer(layer) {
|
||||
if (!lmeState.snapEnabled || !layer || layer instanceof L.Circle || layer instanceof L.Marker) return;
|
||||
const candidates = [];
|
||||
layerManagerCategories().forEach(category => managedRecordsForCategory(category).forEach(record => {
|
||||
if (record.layer === layer) return;
|
||||
lineLatLngGroups(record.layer?.getLatLngs?.() || []).forEach(line => line.forEach(point => candidates.push(point)));
|
||||
const point = record.layer?.getLatLng?.(); if (point) candidates.push(point);
|
||||
}));
|
||||
const snapPoint = point => {
|
||||
const pixel = lmeState.map.latLngToContainerPoint(point);
|
||||
let nearest = null; let distance = lmeState.snapDistancePixels;
|
||||
candidates.forEach(candidate => { const current = pixel.distanceTo(lmeState.map.latLngToContainerPoint(candidate)); if (current < distance) { distance = current; nearest = candidate; } });
|
||||
return nearest ? L.latLng(nearest.lat, nearest.lng) : point;
|
||||
};
|
||||
const transform = value => Array.isArray(value) ? value.map(transform) : snapPoint(value);
|
||||
layer.setLatLngs(transform(layer.getLatLngs()));
|
||||
}
|
||||
|
||||
function scheduleMeasurementRefresh() {
|
||||
@@ -2891,7 +3400,10 @@ function createMapExportGeoJson(options) {
|
||||
});
|
||||
}
|
||||
|
||||
return JSON.stringify({ type: "FeatureCollection", features });
|
||||
const exported = requested.selectedOnly
|
||||
? features.filter(feature => lmeState.managerSelectedObjectIds.has(feature?.properties?._lmeManagerId))
|
||||
: features;
|
||||
return JSON.stringify({ type: "FeatureCollection", features: exported });
|
||||
}
|
||||
|
||||
function appendExportFeatures(target, collection, category, predicate = () => true) {
|
||||
@@ -2936,7 +3448,7 @@ function circleToPolygon(center, radiusMeters) {
|
||||
function createProjectSnapshot(includeCadastralParcels) {
|
||||
const center = lmeState.map.getCenter();
|
||||
return JSON.stringify({
|
||||
schemaVersion: 3,
|
||||
schemaVersion: 4,
|
||||
view: {
|
||||
latitude: center.lat,
|
||||
longitude: center.lng,
|
||||
@@ -2983,12 +3495,7 @@ function loadProjectSnapshot(raw, projectName) {
|
||||
|
||||
const restoredDrawings = L.geoJSON(data.drawings || emptyFeatureCollection(), {
|
||||
pane: "drawingsPane",
|
||||
style: {
|
||||
renderer: lmeState.drawingsRenderer,
|
||||
color: "#f97316",
|
||||
weight: 3,
|
||||
fillOpacity: 0.16
|
||||
},
|
||||
style: storedFeatureStyle,
|
||||
pointToLayer: (feature, latlng) => {
|
||||
const properties = feature?.properties || {};
|
||||
if (properties._lmeShape === "circle" && Number(properties._lmeRadius) > 0) {
|
||||
@@ -3007,6 +3514,7 @@ function loadProjectSnapshot(raw, projectName) {
|
||||
onEachFeature: (feature, layer) => {
|
||||
bindStoredFeaturePopup(feature, layer);
|
||||
annotateDrawingLayer(layer, feature?.properties?._lmeShape);
|
||||
applyStyleFromProperties(layer);
|
||||
}
|
||||
});
|
||||
restoredDrawings.eachLayer(layer => lmeState.drawings.addLayer(layer));
|
||||
@@ -3046,6 +3554,7 @@ function loadProjectSnapshot(raw, projectName) {
|
||||
}
|
||||
refreshImportedMeasurements();
|
||||
refreshDrawingMeasurements();
|
||||
refreshPermanentLabels();
|
||||
|
||||
const projectLayerList = [
|
||||
lmeState.drawings,
|
||||
@@ -3247,6 +3756,8 @@ function resetLayerManagerProjectState() {
|
||||
lmeState.managerRemovedCategories.clear();
|
||||
lmeState.managerObjectOrder = {};
|
||||
lmeState.managerCategoryNames = {};
|
||||
lmeState.managerSelectedObjectIds.clear();
|
||||
lmeState.permanentLabels?.clearLayers();
|
||||
clearManagerHighlight();
|
||||
}
|
||||
|
||||
@@ -3275,8 +3786,11 @@ function bindStoredFeaturePopup(feature, layer) {
|
||||
function updateStoredFeaturePopup(layer, sourceProperties) {
|
||||
const properties = sourceProperties || layer?.feature?.properties || {};
|
||||
const label = properties.name || properties.Name || properties.label || properties.LABEL;
|
||||
if (label) {
|
||||
layer.bindPopup(`<strong>${escapeHtml(label)}</strong>`);
|
||||
const notes = String(properties._lmeNotes || "").trim();
|
||||
const photo = String(properties._lmePhoto || "");
|
||||
if (label || notes || photo) {
|
||||
const image = photo.startsWith("data:image/") ? `<img class="lme-popup-photo" src="${photo}" alt="Foto allegata">` : "";
|
||||
layer.bindPopup(`${label ? `<strong>${escapeHtml(label)}</strong>` : ""}${notes ? `<p>${escapeHtml(notes)}</p>` : ""}${image}`);
|
||||
return;
|
||||
}
|
||||
if (typeof layer?.unbindPopup === "function") {
|
||||
@@ -3299,6 +3813,7 @@ function setBaseLayer(name) {
|
||||
topographic: "Topografica Esri",
|
||||
terrain: "OpenTopoMap",
|
||||
carto: "CARTO Voyager",
|
||||
offline: "Offline, solo dati vettoriali",
|
||||
"azure-road": "Strade Azure Maps",
|
||||
"azure-satellite": "Satellite Azure Maps",
|
||||
"google-satellite": "Satellite Google Maps",
|
||||
@@ -3562,11 +4077,13 @@ function activeCadastreLayers() {
|
||||
|
||||
function clearSelectedParcels() {
|
||||
const count = managedGroupGeoJson(lmeState.selectedParcelsLayer, "selectedParcels").features.length;
|
||||
if (count) rememberMapChange();
|
||||
lmeState.selectedParcelsLayer.clearLayers();
|
||||
clearManagedCategoryState("selectedParcels");
|
||||
updateGpsInsideState();
|
||||
setInfo(count ? `${count} particelle selezionate rimosse.` : "Non ci sono particelle selezionate da rimuovere.");
|
||||
refreshLayerManager();
|
||||
if (count) finishMapChange();
|
||||
}
|
||||
|
||||
function setSelectedParcelsVisible(enabled) {
|
||||
@@ -3608,6 +4125,7 @@ function clearMapElements() {
|
||||
return;
|
||||
}
|
||||
|
||||
rememberMapChange();
|
||||
resetLayerManagerProjectState();
|
||||
lmeState.selectedParcelsLayer.clearLayers();
|
||||
lmeState.gpsParcelLayer.clearLayers();
|
||||
@@ -3621,6 +4139,7 @@ function clearMapElements() {
|
||||
updateGpsInsideState();
|
||||
setInfo("Elementi della mappa rimossi. Sfondo e layer catastali restano attivi.");
|
||||
refreshLayerManager();
|
||||
finishMapChange();
|
||||
}
|
||||
|
||||
function startGps() {
|
||||
@@ -3721,6 +4240,7 @@ function onGpsPosition(position) {
|
||||
if (lmeState.gpsTrailEnabled) {
|
||||
lmeState.gpsTrailPoints.push(latlng);
|
||||
lmeState.gpsTrail.setLatLngs(lmeState.gpsTrailPoints);
|
||||
if (lmeState.gpsTrailPoints.length % 10 === 0) finishMapChange();
|
||||
}
|
||||
|
||||
setText("gpsState", `${latitude.toFixed(6)}, ${longitude.toFixed(6)} - precisione ${Math.round(lmeState.lastAccuracy)} m`);
|
||||
@@ -3782,6 +4302,7 @@ function updateGpsInsideState() {
|
||||
}
|
||||
|
||||
const point = [lmeState.lastPosition[1], lmeState.lastPosition[0]];
|
||||
updateGpsProximity(point);
|
||||
const officialMatch = findContainingPolygon(point, lmeState.selectedParcelsLayer.toGeoJSON())
|
||||
|| findContainingPolygon(point, lmeState.gpsParcelLayer.toGeoJSON());
|
||||
if (officialMatch) {
|
||||
@@ -3808,6 +4329,52 @@ function updateGpsInsideState() {
|
||||
: "Fuori dai poligoni caricati");
|
||||
}
|
||||
|
||||
function updateGpsProximity(coordinates) {
|
||||
if (!lmeState.gpsProximityEnabled || !window.turf) return;
|
||||
const record = lmeState.managerRecords?.get(lmeState.managerHighlightedObjectId)
|
||||
|| [...lmeState.managerSelectedObjectIds].map(id => lmeState.managerRecords?.get(id)).find(Boolean);
|
||||
if (!record?.layer) return;
|
||||
try {
|
||||
const feature = record.layer.toGeoJSON();
|
||||
const boundary = feature.geometry.type.includes("Polygon") ? turf.polygonToLine(feature) : feature;
|
||||
const lines = boundary.type === "FeatureCollection" ? boundary.features : [boundary];
|
||||
let nearest = null;
|
||||
lines.forEach(line => {
|
||||
const candidate = line.geometry.type.includes("Line") ? turf.nearestPointOnLine(line, turf.point(coordinates), { units: "meters" }) : null;
|
||||
if (candidate && (!nearest || candidate.properties.dist < nearest.properties.dist)) nearest = candidate;
|
||||
});
|
||||
if (!nearest) return;
|
||||
const distance = nearest.properties.dist;
|
||||
const bearing = turf.bearing(turf.point(coordinates), nearest);
|
||||
const direction = bearingToCardinal(bearing);
|
||||
const inside = feature.geometry.type.includes("Polygon") && turf.booleanPointInPolygon(turf.point(coordinates), feature);
|
||||
setText("gpsState", `${coordinates[1].toFixed(6)}, ${coordinates[0].toFixed(6)} - bordo ${formatDistance(distance)} ${direction}`);
|
||||
if (lmeState.gpsBoundaryAlertEnabled && lmeState.lastBoundaryState !== null && inside !== lmeState.lastBoundaryState) {
|
||||
navigator.vibrate?.([180, 100, 180]);
|
||||
setInfo(inside ? "Ingresso nell'area selezionata." : "Uscita dall'area selezionata.");
|
||||
}
|
||||
lmeState.lastBoundaryState = inside;
|
||||
} catch { }
|
||||
}
|
||||
|
||||
function bearingToCardinal(value) {
|
||||
const labels = ["N", "NE", "E", "SE", "S", "SO", "O", "NO"];
|
||||
return labels[Math.round(((value % 360) + 360) % 360 / 45) % 8];
|
||||
}
|
||||
|
||||
function saveGpsMeasurementPoint() {
|
||||
if (!lmeState.lastPosition) { setInfo("Attendi una posizione GPS valida."); return; }
|
||||
rememberMapChange();
|
||||
const now = new Date();
|
||||
addDrawingFeature({ type: "Feature", properties: {
|
||||
name: `Rilievo GPS ${now.toLocaleString("it-IT")}`,
|
||||
_lmeAccuracy: lmeState.lastAccuracy,
|
||||
_lmeMeasuredAt: now.toISOString(),
|
||||
_lmeNotes: `Precisione dichiarata: ${Math.round(lmeState.lastAccuracy)} m`
|
||||
}, geometry: { type: "Point", coordinates: [lmeState.lastPosition[1], lmeState.lastPosition[0]] } }, true);
|
||||
refreshLayerManager(); finishMapChange(); setInfo("Punto GPS salvato con precisione, data e ora.");
|
||||
}
|
||||
|
||||
function gmlParcelsToGeoJson(xmlText) {
|
||||
const xml = new DOMParser().parseFromString(xmlText, "text/xml");
|
||||
const members = Array.from(xml.getElementsByTagNameNS("*", "member"));
|
||||
|
||||
Vendored
+37
@@ -0,0 +1,37 @@
|
||||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).turf={})}(this,(function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function n(t){if(Array.isArray(t))return t}function r(t,e,n){return e=l(e),function(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,c()?Reflect.construct(e,n||[],l(t).constructor):e.apply(t,n))}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,y(r.key),r)}}function s(t,e,n){return e&&o(t.prototype,e),n&&o(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function a(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=_(t))||e){n&&(t=n);var r=0,i=function(){};return{s:i,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}function u(t,e,n){return(e=y(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function l(t){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},l(t)}function h(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&p(t,e)}function c(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(c=function(){return!!t})()}function f(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}function g(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function p(t,e){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},p(t,e)}function v(t,e){return n(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,i,o,s,a=[],u=!0,l=!1;try{if(o=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);u=!0);}catch(t){l=!0,i=t}finally{try{if(!u&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(l)throw i}}return a}}(t,e)||_(t,e)||g()}function d(t){return function(t){if(Array.isArray(t))return e(t)}(t)||f(t)||_(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function m(t){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},m(t)}function _(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var x=6371008.8,E={centimeters:100*x,centimetres:100*x,degrees:360/(2*Math.PI),feet:3.28084*x,inches:39.37*x,kilometers:x/1e3,kilometres:x/1e3,meters:x,metres:x,miles:x/1609.344,millimeters:1e3*x,millimetres:1e3*x,nauticalmiles:x/1852,radians:1,yards:1.0936*x},k={acres:247105e-9,centimeters:1e4,centimetres:1e4,feet:10.763910417,hectares:1e-4,inches:1550.003100006,kilometers:1e-6,kilometres:1e-6,meters:1,metres:1,miles:386e-9,nauticalmiles:2.9155334959812285e-7,millimeters:1e6,millimetres:1e6,yards:1.195990046};function b(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={type:"Feature"};return(0===Line truncated
|
||||
/*!
|
||||
* Copyright (c) 2019, Dane Springmeyer
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in
|
||||
* the documentation and/or other materials provided with the
|
||||
* distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
|
||||
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
|
||||
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
function ta(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must specify at least 2 geometries");var r=Rs.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)}function ea(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.stringify(n.properties||{}),i=v(t,4),o=i[0],s=i[1],a=i[2],u=i[3],l=(s+u)/2,h=(o+a)/2,c=2*e/ut([o,l],[a,l],n)*(a-o),f=2*e/ut([h,s],[h,u],n)*(u-s),g=c/2,p=2*g,d=Math.sqrt(3)/2*f,y=a-o,m=u-s,_=3/4*p,x=d,E=(y-p)/(p-g/2),k=Math.floor(E),b=(k*_-g/2-y)/2-g/2+_/2,w=Math.floor((m-d)/d),I=(m-w*d)/2,N=w*d-m>d/2;N&&(I-=d/4);for(var S=[],M=[],L=0;L<6;L++){var P=2*Math.PI/6*L;S.push(Math.cos(P)),M.push(Math.sin(P))}for(var T=[],O=0;O<=k;O++)for(var R=0;R<=w;R++){var A=O%2==1;if((0!==R||!A)&&(0!==R||!N)){var D=O*_+o-b,F=R*x+s+I;if(A&&(F-=d/2),!0===n.triangles)ra([D,F],c/2,f/2,JSON.parse(r),S,M).forEach((function(t){n.mask?ta(C([n.mask,t]))&&T.push(t):T.push(t)}));else{var q=na([D,F],c/2,f/2,JSON.parse(r),S,M);n.mask?ta(C([n.mask,q]))&&T.push(q):T.push(q)}}}return C(T)}function na(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=t[0]+e*i[a],l=t[1]+n*o[a];s.push([u,l])}return s.push(s[0].slice()),S([s],r)}function ra(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=[];u.push(t),u.push([t[0]+e*i[a],t[1]+n*o[a]]),u.push([t[0]+e*i[(a+1)%6],t[1]+n*o[(a+1)%6]]),u.push(t),s.push(S([u],r))}return s}function ia(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n.mask&&!n.units&&(n.units="kilometers");for(var r=[],i=t[0],o=t[1],s=t[2],a=t[3],u=e/ut([i,o],[s,o],n)*(s-i),l=e/ut([i,o],[i,a],n)*(a-o),h=s-i,c=a-o,f=Math.floor(h/u),g=(c-Math.floor(c/l)*l)/2,p=i+(h-f*u)/2;p<=s;){for(var v=o+g;v<=a;){var d=I([p,v],n.properties);n.mask?Cn(d,n.mask)&&r.push(d):r.push(d),v+=l}p+=u}return C(r)}function oa(t,e,n){for(var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=[],o=t[0],s=t[1],a=t[2],u=t[3],l=a-o,h=j(e,r.units,"degrees"),c=u-s,f=j(n,r.units,"degrees"),g=Math.floor(Math.abs(l)/h),p=Math.floor(Math.abs(c)/f),v=(c-p*f)/2,d=o+(l-g*h)/2,y=0;y<g;y++){for(var m=s+v,_=0;_<p;_++){var x=S([[[d,m],[d,m+f],[d+h,m+f],[d+h,m],[d,m]]],r.properties);r.mask?Oe(r.mask,x)&&i.push(x):i.push(x),m+=f}d+=h}return C(i)}function sa(t,e){return oa(t,e,e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function aa(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=[],i=e/ut([t[0],t[1]],[t[2],t[1]],n)*(t[2]-t[0]),o=e/ut([t[0],t[1]],[t[0],t[3]],n)*(t[3]-t[1]),s=0,a=t[0];a<=t[2];){for(var u=0,l=t[1];l<=t[3];){var h=null,c=null;s%2==0&&u%2==0?(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)):s%2==0&&u%2==1?(h=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties)):u%2==0&&s%2==1?(h=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties),c=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties)):u%2==1&&s%2==1&&(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)),n.mask?(ta(C([n.mask,h]))&&r.push(h),ta(C([n.mask,c]))&&r.push(c)):(r.push(h),r.push(c)),l+=o,u++}s++,a+=i}return C(r)}
|
||||
/*!
|
||||
* MarchingSquaresJS
|
||||
* version 1.3.3
|
||||
* https://github.com/RaumZeit/MarchingSquares.js
|
||||
*
|
||||
* @license GNU Affero General Public License.
|
||||
* Copyright (c) 2015-2019 Ronny Lorenz <ronny@tbi.univie.ac.at>
|
||||
*/
|
||||
function ua(t,e,n){return t<e?(n-t)/(e-t):(t-n)/(t-e)}function la(t,e,n,r){var i;return n>r&&(i=n,n=r,r=i),t<e?t<n?(n-t)/(e-t):(r-t)/(e-t):t>r?(t-r)/(t-e):(t-n)/(t-e)}function ha(t,e,n,r){return t<e?(n-t)/(e-t):(t-r)/(t-e)}function ca(t,e,n,r){return t<e?(r-t)/(e-t):(t-n)/(t-e)}function fa(){this.successCallback=null,this.verbose=!1,this.polygons=!1,this.polygons_full=!1,this.linearRing=!0,this.noQuadTree=!1,this.noFrame=!1}function ga(t,e,n,r){var i=[];return t.polygons.forEach((function(t){t.forEach((function(t){t[0]+=e,t[1]+=n})),r.linearRing&&t.push(t[0]),i.push(t)})),i}function pa(t,e,n,r){return 0===n?(t+=1,e+=r[0][1]):1===n?t+=r[0][0]:2===n?e+=r[0][1]:3===n&&(t+=r[0][0],e+=1),[t,e]}function va(t,e,n){return 0===n?t++:1===n||(2===n?e++:3===n&&(t++,e++)),[t,e]}function da(t,e,n,r,i){var o=r,s=i,a=0,u=0;if(this.x=e,this.y=n,this.lowerBound=null,this.upperBound=null,this.childA=null,this.childB=null,this.childC=null,this.childD=null,1===r&&1===i)this.lowerBound=Math.min(t[n][e],t[n][e+1],t[n+1][e+1],t[n+1][e]),this.upperBound=Math.max(t[n][e],t[n][e+1],t[n+1][e+1],t[n+1][e]);else{if(r>1){for(;0!==o;)o>>=1,a++;r===1<<a-1&&a--,o=1<<a-1}if(i>1){for(;0!==s;)s>>=1,u++;i===1<<u-1&&u--,s=1<<u-1}this.childA=new da(t,e,n,o,s),this.lowerBound=this.childA.lowerBound,this.upperBound=this.childA.upperBound,r-o>0&&(this.childB=new da(t,e+o,n,r-o,s),this.lowerBound=Math.min(this.lowerBound,this.childB.lowerBound),this.upperBound=Math.max(this.upperBound,this.childB.upperBound),i-s>0&&(this.childC=new da(t,e+o,n+s,r-o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childC.lowerBound),this.upperBound=Math.max(this.upperBound,this.childC.upperBound))),i-s>0&&(this.childD=new da(t,e,n+s,o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childD.lowerBound),this.upperBound=Math.max(this.upperBound,this.childD.upperBound))}}function ya(t){var e,n;if(!t)throw new Error("data is required");if(!Array.isArray(t)||!Array.isArray(t[0]))throw new Error("data must be scalar field, i.e. array of arrays");if(t.length<2)throw new Error("data must contain at least two rows");if((n=t[0].length)<2)throw new Error("data must contain at least two columns");for(e=1;e<t.length;e++){if(!Array.isArray(t[e]))throw new Error("Row "+e+" is not an array");if(t[e].length!=n)throw new Error("unequal row lengths detected, please provide a regular grid")}this.data=t,this.root=new da(t,0,0,t[0].length-1,t.length-1)}function ma(t,e,n){var r,i,o,s=!1,a=!1,u=null,l=null,h=null,c=null,f=null,g=[];if(!t)throw new Error("data is required");if(null==e)throw new Error("threshold is required");if(n&&"object"!==m(n))throw new Error("options must be an object");if(r=function(t){var e,n,r,i,o;for(i=new fa,t=t||{},o=Object.keys(i),e=0;e<o.length;e++)null!=(r=t[n=o[e]])&&(i[n]=r);return i.polygons_full=!i.polygons,i.interpolate=ua,i}(n),t instanceof ya)u=t,l=t.root,h=t.data,r.noQuadTree||(s=!0);else{if(!Array.isArray(t)||!Array.isArray(t[0]))throw new Error("input is neither array of arrays nor object retrieved from 'QuadTree()'");h=t}if(Array.isArray(e)){for(a=!0,r.noQuadTree||(s=!0),i=0;i<e.length;i++)if(isNaN(+e[i]))throw new Error("threshold["+i+"] is not a number")}else{if(isNaN(+e))throw new Error("threshold must be a number or array of numbers");e=[e]}return s&&!l&&(u=new ya(h),l=u.root,h=u.data),r.verbose&&(r.polygons?console.log("MarchingSquaresJS-isoLines: returning single lines (polygons) for each grid cell"):console.log("MarchingSquaresJS-isoLines: returning line paths (polygons) for entire data grid"),a&&console.log("MarchingSquaresJS-isoLines: multiple lines requested, returning array of line paths instead of lines for a single threshold")),e.forEach((function(t,e){if(f=[],r.threshold=t,r.verbose&&console.log("MarchingSquaresJS-isoLines: computing iso lines for threshold "+t),r.polygons)if(s)l.cellsBelowThreshold(r.threshold,!0).forEach((function(t){f=f.concat(ga(_a(h,t.x,t.y,r),t.x,t.y,r))}));else for(o=0;o<h.length-1;++o)for(e=0;e<h[0].length-1;++e)f=f.concat(ga(_a(h,e,o,r),e,o,r));else{for(c=[],e=0;e<h[0].length-1;++e)c[e]=[];if(s)l.cellsBelowThreshold(r.threshold,!1).forEach((function(t){c[t.x][t.y]=_a(h,t.x,t.y,r)}));else for(e=0;e<h[0].length-1;++e)for(o=0;o<h.length-1;++o)c[e][o]=_a(h,e,o,r);f=function(t,e,n){var r,i,o,s,a,u,l,h,c,f,g,p,v,d,y,_=[],x=t.length-1,E=t[0].length-1,k=["right","bottom","left","top"],b=[0,-1,0,1],w=[-1,0,1,0],I={bottom:1,left:2,top:3,right:0};return n.noFrame||function(t,e){var n,r,i,o,s;for(n=!0,r=t[0].length,i=t.length,s=0;s<i;s++)if(t[s][0]>=e||t[s][r-1]>=e){n=!1;break}if(n&&(t[i-1][0]>=e||t[i-1][r-1]>=e)&&(n=!1),n)for(o=0;o<r-1;o++)if(t[0][o]>=e||t[i-1][o]>e){n=!1;break}return n}(t,n.threshold)&&(n.linearRing?_.push([[0,0],[0,x],[E,x],[E,0],[0,0]]):_.push([[0,0],[0,x],[E,x],[E,0]])),e.forEach((function(t,N){t.forEach((function(t,S){for(r=null,i=0;i<4;i++)if(r=k[i],"object"===m(t.edges[r])){for(a=[],o=t.edges[r],u=r,l=N,h=S,c=!1,f=[N+o.path[0][0],S+o.path[0][1]],a.push(f);!c&&"object"===m((s=e[l][h]).edges[u]);)iLine truncated
|
||||
Reference in new issue
Block a user