6098 lines
235 KiB
JavaScript
6098 lines
235 KiB
JavaScript
(function () {
|
||
"use strict";
|
||
|
||
const DEFAULT_VIEW = {
|
||
center: [39.9042, 116.4074],
|
||
zoom: 12
|
||
};
|
||
|
||
const coordinateSystems = window.MapStudioCoordinates;
|
||
const coordinateSystemSelect = document.getElementById("coordinateSystemSelect");
|
||
let selectedCoordinateSystem = coordinateSystems
|
||
? coordinateSystems.normalizeSystemId(coordinateSystemSelect?.value)
|
||
: "wgs84";
|
||
const coordinateReadoutFormatButton = document.getElementById("coordinateReadoutFormat");
|
||
let coordinateReadoutFormat = "decimal";
|
||
|
||
const bootParams = new URLSearchParams(window.location.search);
|
||
const mapServiceBase = (
|
||
bootParams.get("server") ||
|
||
(window.location.protocol === "file:" ? "http://127.0.0.1:8081" : "")
|
||
).replace(/\/+$/, "");
|
||
const mapServiceUrl = (path) => {
|
||
const relativePath = String(path).replace(/^\/+/, "");
|
||
return mapServiceBase ? mapServiceBase + "/" + relativePath : relativePath;
|
||
};
|
||
|
||
const FallbackTileLayer = L.TileLayer.extend({
|
||
initialize(urls, options) {
|
||
this.urls = urls;
|
||
L.TileLayer.prototype.initialize.call(this, urls[0], options);
|
||
},
|
||
createTile(coords, done) {
|
||
const tile = document.createElement("img");
|
||
tile.alt = "";
|
||
tile.setAttribute("role", "presentation");
|
||
let index = 0;
|
||
|
||
const tryNext = () => {
|
||
tile.src = this.urls[index]
|
||
.replace("{z}", coords.z)
|
||
.replace("{x}", coords.x)
|
||
.replace("{y}", coords.y);
|
||
};
|
||
|
||
tile.onload = () => done(null, tile);
|
||
tile.onerror = () => {
|
||
index += 1;
|
||
if (index < this.urls.length) tryNext();
|
||
else done(new Error("tile unavailable"), tile);
|
||
};
|
||
|
||
tryNext();
|
||
return tile;
|
||
}
|
||
});
|
||
const providerLabels = {
|
||
clean: "简洁底图",
|
||
standard: "标准地图",
|
||
topo: "地形图",
|
||
satellite: "卫星影像",
|
||
relief: "地形晕渲",
|
||
"tdt-vec": "天地图矢量",
|
||
"tdt-ter": "天地图地形",
|
||
"tdt-img": "天地图影像"
|
||
};
|
||
|
||
const baseLayers = {
|
||
clean: new FallbackTileLayer([
|
||
mapServiceUrl("tiles/clean/{z}/{x}/{y}.png")
|
||
], {
|
||
maxZoom: 19,
|
||
attribution: "Tiles © Esri — Esri, HERE, Garmin, OpenStreetMap contributors"
|
||
}),
|
||
standard: new FallbackTileLayer([
|
||
mapServiceUrl("tiles/osm/{z}/{x}/{y}.png")
|
||
], {
|
||
maxZoom: 19,
|
||
attribution: "© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors"
|
||
}),
|
||
topo: new FallbackTileLayer([
|
||
mapServiceUrl("tiles/topo-preview/{z}/{x}/{y}.png")
|
||
], {
|
||
maxZoom: 19,
|
||
maxNativeZoom: 13,
|
||
attribution: "Tiles © Esri — Esri, HERE, Garmin, OpenStreetMap contributors"
|
||
}),
|
||
satellite: new FallbackTileLayer([
|
||
mapServiceUrl("tiles/satellite/{z}/{x}/{y}.png")
|
||
], {
|
||
maxZoom: 19,
|
||
attribution: "Tiles © Esri — Source: Esri, Maxar, Earthstar Geographics"
|
||
}),
|
||
relief: new FallbackTileLayer([
|
||
mapServiceUrl("tiles/osm/{z}/{x}/{y}.png")
|
||
], {
|
||
maxZoom: 19,
|
||
attribution: "© OpenStreetMap contributors | Hillshade generated in browser from AWS Terrain Tiles"
|
||
}),
|
||
"tdt-vec": new FallbackTileLayer([
|
||
mapServiceUrl("tiles/tdt-vec/{z}/{x}/{y}.png")
|
||
], {
|
||
maxZoom: 18,
|
||
attribution: "© 天地图"
|
||
}),
|
||
"tdt-ter": new FallbackTileLayer([
|
||
mapServiceUrl("tiles/tdt-ter/{z}/{x}/{y}.png")
|
||
], {
|
||
maxZoom: 18,
|
||
attribution: "© 天地图"
|
||
}),
|
||
"tdt-img": new FallbackTileLayer([
|
||
mapServiceUrl("tiles/tdt-img/{z}/{x}/{y}.png")
|
||
], {
|
||
maxZoom: 18,
|
||
attribution: "© 天地图"
|
||
})
|
||
};
|
||
|
||
const map = L.map("map", {
|
||
zoomControl: false,
|
||
preferCanvas: true,
|
||
worldCopyJump: true
|
||
}).setView(DEFAULT_VIEW.center, DEFAULT_VIEW.zoom);
|
||
|
||
const waterPane = map.createPane("waterPane");
|
||
waterPane.style.zIndex = "420";
|
||
waterPane.style.pointerEvents = "none";
|
||
const vegetationPane = map.createPane("vegetationPane");
|
||
vegetationPane.style.zIndex = "410";
|
||
vegetationPane.style.pointerEvents = "none";
|
||
const portPane = map.createPane("portPane");
|
||
portPane.style.zIndex = "460";
|
||
portPane.style.pointerEvents = "auto";
|
||
const administrativeBoundaryPane = map.createPane("administrativeBoundaryPane");
|
||
administrativeBoundaryPane.style.zIndex = "675";
|
||
administrativeBoundaryPane.style.pointerEvents = "none";
|
||
const localVectorPane = map.createPane("localVectorPane");
|
||
localVectorPane.style.zIndex = "440";
|
||
localVectorPane.style.pointerEvents = "none";
|
||
const tdtLabelPane = map.createPane("tdtLabelPane");
|
||
tdtLabelPane.style.zIndex = "680";
|
||
tdtLabelPane.style.pointerEvents = "none";
|
||
const tdtBoundaryPane = map.createPane("tdtBoundaryPane");
|
||
tdtBoundaryPane.style.zIndex = "665";
|
||
tdtBoundaryPane.style.pointerEvents = "none";
|
||
const railTilePane = map.createPane("railTilePane");
|
||
railTilePane.style.zIndex = "450";
|
||
railTilePane.style.pointerEvents = "none";
|
||
|
||
L.control.scale({ position: "bottomleft", metric: true, imperial: false, maxWidth: 120 }).addTo(map);
|
||
map.attributionControl.addAttribution(
|
||
'Rail / water © <a href="https://openfreemap.org">OpenFreeMap</a>, ' +
|
||
'<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
|
||
);
|
||
|
||
let currentBaseKey = "clean";
|
||
let previousBaseBeforeContour = "standard";
|
||
let railLoadSequence = 0;
|
||
let renderedRailFeatureIds = new Set();
|
||
let loadedRailElements = [];
|
||
let localRailRendered = false;
|
||
let localRailViewKey = "";
|
||
let railPendingPollTimer = null;
|
||
let waterLoadSequence = 0;
|
||
const OPENFREEMAP_SOURCE_MAX_ZOOM = 14;
|
||
let renderedWaterFeatureIds = new Set();
|
||
let renderedPortFeatureIds = new Set();
|
||
let renderedVegetationFeatureIds = new Set();
|
||
let loadedWaterElements = [];
|
||
let loadedPortElements = [];
|
||
let loadedVegetationElements = [];
|
||
let waterRefreshTimer = null;
|
||
let waterPendingPollTimer = null;
|
||
let boundaryLoadSequence = 0;
|
||
let boundaryRefreshTimer = null;
|
||
let lastAdministrativeBoundaryElements = [];
|
||
let localVectorLoadSequence = 0;
|
||
let localVectorRefreshTimer = null;
|
||
let localVectorManifest = null;
|
||
let localVector25Manifest = null;
|
||
let localVectorMissingTiles = new Set();
|
||
let localVector25MissingTiles = new Set();
|
||
let localVectorFeatures = [];
|
||
let localVectorDisplayedZoom = null;
|
||
let terrainFeatureSequence = 0;
|
||
let terrainFeatureTimer = null;
|
||
let toastTimer = null;
|
||
let elevationTimer = null;
|
||
let elevationRequest = 0;
|
||
|
||
const statusText = document.getElementById("statusText");
|
||
const statusPill = document.querySelector(".topbar-status");
|
||
const coordReadout = document.getElementById("coordReadout");
|
||
const zoomReadout = document.getElementById("zoomReadout");
|
||
const baseReadout = document.getElementById("baseReadout");
|
||
const railStatus = document.getElementById("railStatus");
|
||
const railTileStatus = document.getElementById("railTileStatus");
|
||
const nationalRailStatus = document.getElementById("nationalRailStatus");
|
||
const metroStatus = document.getElementById("metroStatus");
|
||
const terrainFeatureStatus = document.getElementById("terrainFeatureStatus");
|
||
const waterStatus = document.getElementById("waterStatus");
|
||
const portStatus = document.getElementById("portStatus");
|
||
const vegetationStatus = document.getElementById("vegetationStatus");
|
||
const boundaryStatus = document.getElementById("boundaryStatus");
|
||
const localVectorStatus = document.getElementById("localVectorStatus");
|
||
const toast = document.getElementById("toast");
|
||
|
||
const cleanLabelLayer = L.tileLayer(
|
||
mapServiceUrl("tiles/clean-labels/{z}/{x}/{y}.png"),
|
||
{
|
||
maxZoom: 19,
|
||
opacity: 0.86,
|
||
zIndex: 2,
|
||
attribution: "Labels © Esri"
|
||
}
|
||
);
|
||
|
||
const tdtVectorLabelLayer = L.tileLayer(
|
||
mapServiceUrl("tiles/tdt-vec-label/{z}/{x}/{y}.png"),
|
||
{ maxZoom: 18, opacity: 0.95, pane: "tdtLabelPane", attribution: "© 天地图" }
|
||
);
|
||
const tdtTerrainLabelLayer = L.tileLayer(
|
||
mapServiceUrl("tiles/tdt-ter-label/{z}/{x}/{y}.png"),
|
||
{ maxZoom: 18, opacity: 0.95, pane: "tdtLabelPane", attribution: "© 天地图" }
|
||
);
|
||
const tdtImageryLabelLayer = L.tileLayer(
|
||
mapServiceUrl("tiles/tdt-img-label/{z}/{x}/{y}.png"),
|
||
{ maxZoom: 18, opacity: 0.95, pane: "tdtLabelPane", attribution: "© 天地图" }
|
||
);
|
||
const tdtBoundaryLayer = L.tileLayer(
|
||
mapServiceUrl("tiles/tdt-boundary/{z}/{x}/{y}.png"),
|
||
{ maxZoom: 18, opacity: 0.82, pane: "tdtBoundaryPane", attribution: "© 天地图" }
|
||
);
|
||
|
||
baseLayers.clean.addTo(map);
|
||
cleanLabelLayer.addTo(map);
|
||
|
||
const railTileLayer = L.tileLayer(mapServiceUrl("tiles/railway/{z}/{x}/{y}.png"), {
|
||
maxZoom: 19,
|
||
opacity: 0.96,
|
||
pane: "railTilePane",
|
||
zIndex: 1,
|
||
className: "railway-infra-layer",
|
||
attribution: "Railway rendering: <a href=\"https://www.openrailwaymap.org/\">OpenRailwayMap</a>"
|
||
});
|
||
|
||
const nationalRailGroup = L.layerGroup();
|
||
const metroGroup = L.layerGroup();
|
||
const waterLayerGroup = L.layerGroup();
|
||
const portLayerGroup = L.layerGroup();
|
||
const vegetationLayerGroup = L.layerGroup();
|
||
const administrativeBoundaryLayer = L.layerGroup();
|
||
const localVectorLayer = L.layerGroup();
|
||
const terrainFeatureLayer = L.layerGroup();
|
||
|
||
const gridConfig = {
|
||
interval: 0,
|
||
startLon: 0,
|
||
startLat: 0,
|
||
color: "#2f5543",
|
||
width: 0.7,
|
||
projected: false
|
||
};
|
||
const contourConfig = {
|
||
interval: 20,
|
||
startElevation: 0,
|
||
boldEvery: 5,
|
||
color: "#76512d",
|
||
width: 1,
|
||
boldWidth: 2.2
|
||
};
|
||
const boundaryConfig = {
|
||
highColor: "#8f2e1f",
|
||
middleColor: "#bd4f2e",
|
||
localColor: "#d47a2c"
|
||
};
|
||
const themeColors = {
|
||
national: "#5c43c6",
|
||
metro: "#e15b3c",
|
||
water: "#4fb6dc",
|
||
port: "#166a86",
|
||
vegetation: "#68a94f",
|
||
terrainPeak: "#a45d2c",
|
||
terrainValley: "#2e628d",
|
||
localRoads: "#d16a35",
|
||
localRailways: "#6847a6",
|
||
localWater: "#378db7",
|
||
localAdministration: "#98462e",
|
||
localSettlements: "#795334",
|
||
localVegetation: "#4a8050",
|
||
localTerrain: "#84633f",
|
||
localFacilities: "#8b7358",
|
||
localHeritage: "#a4544f"
|
||
};
|
||
const themeColorInputs = {
|
||
national: "nationalRailColor",
|
||
metro: "metroColor",
|
||
water: "waterElementColor",
|
||
port: "portElementColor",
|
||
vegetation: "vegetationElementColor",
|
||
terrainPeak: "terrainPeakColor",
|
||
terrainValley: "terrainValleyColor",
|
||
localRoads: "localRoadsColor",
|
||
localRailways: "localRailwaysColor",
|
||
localWater: "localWaterColor",
|
||
localAdministration: "localAdministrationColor",
|
||
localSettlements: "localSettlementsColor",
|
||
localVegetation: "localVegetationColor",
|
||
localTerrain: "localTerrainColor",
|
||
localFacilities: "localFacilitiesColor",
|
||
localHeritage: "localHeritageColor"
|
||
};
|
||
let railwayLineStyle = "railway";
|
||
let metroLineStyle = "plain";
|
||
|
||
const chooseGridStep = (span, targetLines) => {
|
||
const rough = Math.max(span / targetLines, 0.000001);
|
||
const steps = [30, 20, 10, 5, 2, 1, 0.5, 0.25, 0.1, 0.05, 0.02, 0.01, 0.005, 0.002, 0.001];
|
||
return steps.find((step) => step <= rough) || steps[steps.length - 1];
|
||
};
|
||
|
||
const chooseMetricGridStep = (span, targetLines) => {
|
||
const rough = Math.max(span / targetLines, 1);
|
||
const power = Math.pow(10, Math.floor(Math.log10(rough)));
|
||
const normalized = rough / power;
|
||
const nice = normalized <= 1 ? 1 : normalized <= 2 ? 2 : normalized <= 5 ? 5 : 10;
|
||
return nice * power;
|
||
};
|
||
|
||
const formatDmsValue = (value, axis, secondsPrecision = 0) => {
|
||
const direction = axis === "lat" ? (value >= 0 ? "N" : "S") : (value >= 0 ? "E" : "W");
|
||
const absolute = Math.abs(value);
|
||
const precision = Math.max(0, Math.min(4, Number(secondsPrecision) || 0));
|
||
let roundedSeconds = Number((absolute * 3600).toFixed(precision));
|
||
let degrees = Math.floor(roundedSeconds / 3600);
|
||
roundedSeconds -= degrees * 3600;
|
||
let minutes = Math.floor(roundedSeconds / 60);
|
||
let seconds = roundedSeconds - minutes * 60;
|
||
if (seconds >= 60) {
|
||
minutes += 1;
|
||
seconds -= 60;
|
||
}
|
||
if (minutes >= 60) {
|
||
degrees += 1;
|
||
minutes -= 60;
|
||
}
|
||
const secondWidth = precision ? 2 + 1 + precision : 2;
|
||
const secondText = seconds.toFixed(precision).padStart(secondWidth, "0");
|
||
return degrees + "°" + String(minutes).padStart(2, "0") + "′" + secondText + "″" + direction;
|
||
};
|
||
|
||
const formatGridValue = (value, axis, step) => {
|
||
const secondsPrecision = step < 1 / 3600
|
||
? Math.min(3, Math.max(1, Math.ceil(-Math.log10(step * 3600))))
|
||
: 0;
|
||
return formatDmsValue(value, axis, secondsPrecision);
|
||
};
|
||
|
||
const formatMetricGridValue = (value) => {
|
||
const rounded = Math.abs(value) < 0.5 ? 0 : Math.round(value);
|
||
return rounded.toLocaleString("en-US") + " m";
|
||
};
|
||
|
||
const gridCoordinateSystemId = () => selectedCoordinateSystem || "wgs84";
|
||
|
||
const gridSystemCoordinates = (latlng) => coordinateSystems
|
||
? coordinateSystems.toSystemCoordinates(latlng.lat, latlng.lng, gridCoordinateSystemId())
|
||
: { kind: "geographic", lat: latlng.lat, lng: latlng.lng };
|
||
|
||
const gridWgs84Coordinates = (first, second) => coordinateSystems
|
||
? coordinateSystems.wgs84FromSystemCoordinates(first, second, gridCoordinateSystemId())
|
||
: { lat: first, lng: second };
|
||
|
||
const GridWithLabels = L.GridLayer.extend({
|
||
createTile(coords) {
|
||
const tile = document.createElement("canvas");
|
||
const size = this.getTileSize();
|
||
tile.width = size.x;
|
||
tile.height = size.y;
|
||
if (document.body.classList.contains("hide-map-grid")) return tile;
|
||
|
||
const ctx = tile.getContext("2d");
|
||
const nw = map.unproject([coords.x * size.x, coords.y * size.y], coords.z);
|
||
const se = map.unproject([(coords.x + 1) * size.x, (coords.y + 1) * size.y], coords.z);
|
||
const tileOrigin = L.point(coords.x * size.x, coords.y * size.y);
|
||
const projectPoint = (lat, lng) =>
|
||
map.project(L.latLng(lat, lng), coords.z).subtract(tileOrigin);
|
||
|
||
const coordinateSamples = [
|
||
nw,
|
||
L.latLng(nw.lat, (nw.lng + se.lng) / 2),
|
||
L.latLng(nw.lat, se.lng),
|
||
L.latLng((nw.lat + se.lat) / 2, nw.lng),
|
||
L.latLng((nw.lat + se.lat) / 2, (nw.lng + se.lng) / 2),
|
||
L.latLng((nw.lat + se.lat) / 2, se.lng),
|
||
L.latLng(se.lat, nw.lng),
|
||
L.latLng(se.lat, (nw.lng + se.lng) / 2),
|
||
se
|
||
].map(gridSystemCoordinates);
|
||
const projectedGrid = coordinateSamples[0].kind === "projected";
|
||
const firstValues = coordinateSamples.map((value) => projectedGrid ? value.x : value.lng);
|
||
const secondValues = coordinateSamples.map((value) => projectedGrid ? value.y : value.lat);
|
||
const firstMin = Math.min(...firstValues);
|
||
const firstMax = Math.max(...firstValues);
|
||
const secondMin = Math.min(...secondValues);
|
||
const secondMax = Math.max(...secondValues);
|
||
const firstSpan = Math.max(firstMax - firstMin, projectedGrid ? 1 : 0.000001);
|
||
const secondSpan = Math.max(secondMax - secondMin, projectedGrid ? 1 : 0.000001);
|
||
const firstStep = projectedGrid
|
||
? Math.max(gridConfig.interval || chooseMetricGridStep(firstSpan, 3), firstSpan / 140)
|
||
: Math.max(gridConfig.interval || chooseGridStep(firstSpan, 3), firstSpan / 140);
|
||
const secondStep = projectedGrid
|
||
? Math.max(gridConfig.interval || chooseMetricGridStep(secondSpan, 2.5), secondSpan / 140)
|
||
: Math.max(gridConfig.interval || chooseGridStep(secondSpan, 2.5), secondSpan / 140);
|
||
const firstPad = firstSpan * 0.08 + firstStep;
|
||
const secondPad = secondSpan * 0.08 + secondStep;
|
||
|
||
ctx.clearRect(0, 0, size.x, size.y);
|
||
ctx.strokeStyle = gridConfig.color;
|
||
ctx.fillStyle = gridConfig.color;
|
||
ctx.lineWidth = gridConfig.width;
|
||
ctx.font = "9px Inter, sans-serif";
|
||
|
||
const drawGridLine = (points, label, labelAxis) => {
|
||
if (!points.length) return;
|
||
ctx.beginPath();
|
||
points.forEach((point, index) => {
|
||
if (index === 0) ctx.moveTo(point.x, point.y);
|
||
else ctx.lineTo(point.x, point.y);
|
||
});
|
||
ctx.stroke();
|
||
if (coords.z < 5 || !label) return;
|
||
const inside = points.filter((point) =>
|
||
point.x >= 4 && point.x <= size.x - 4 && point.y >= 4 && point.y <= size.y - 4
|
||
);
|
||
if (!inside.length) return;
|
||
const anchor = labelAxis === "vertical"
|
||
? inside.reduce((best, point) => point.y < best.y ? point : best, inside[0])
|
||
: inside.reduce((best, point) => point.x < best.x ? point : best, inside[0]);
|
||
if (labelAxis === "vertical") ctx.fillText(label, anchor.x + 3, Math.max(12, anchor.y - 4));
|
||
else ctx.fillText(label, Math.max(5, anchor.x + 3), Math.max(11, anchor.y - 4));
|
||
};
|
||
|
||
const firstStart = Math.ceil((firstMin - firstPad - gridConfig.startLon) / firstStep) * firstStep + gridConfig.startLon;
|
||
for (let value = firstStart; value <= firstMax + firstPad; value += firstStep) {
|
||
const points = [];
|
||
for (let sample = 0; sample <= 24; sample += 1) {
|
||
const secondValue = secondMin - secondPad + (secondSpan + secondPad * 2) * sample / 24;
|
||
const wgs = projectedGrid
|
||
? gridWgs84Coordinates(secondValue, value)
|
||
: gridWgs84Coordinates(secondValue, value);
|
||
points.push(projectPoint(wgs.lat, wgs.lng));
|
||
}
|
||
drawGridLine(
|
||
points,
|
||
projectedGrid
|
||
? formatMetricGridValue(value)
|
||
: formatGridValue(value, "lng", firstStep),
|
||
"vertical"
|
||
);
|
||
}
|
||
|
||
const secondStart = Math.ceil((secondMin - secondPad - gridConfig.startLat) / secondStep) * secondStep + gridConfig.startLat;
|
||
for (let value = secondStart; value <= secondMax + secondPad; value += secondStep) {
|
||
const points = [];
|
||
for (let sample = 0; sample <= 24; sample += 1) {
|
||
const firstValue = firstMin - firstPad + (firstSpan + firstPad * 2) * sample / 24;
|
||
const wgs = projectedGrid
|
||
? gridWgs84Coordinates(value, firstValue)
|
||
: gridWgs84Coordinates(value, firstValue);
|
||
points.push(projectPoint(wgs.lat, wgs.lng));
|
||
}
|
||
drawGridLine(
|
||
points,
|
||
projectedGrid
|
||
? formatMetricGridValue(value)
|
||
: formatGridValue(value, "lat", secondStep),
|
||
"horizontal"
|
||
);
|
||
}
|
||
|
||
return tile;
|
||
}
|
||
});
|
||
|
||
const gridLayer = new GridWithLabels({
|
||
zIndex: 430,
|
||
className: "map-grid-layer",
|
||
attribution: "Grid generated in browser"
|
||
}).addTo(map);
|
||
|
||
const syncGridCoordinateUi = () => {
|
||
const system = coordinateSystems
|
||
? coordinateSystems.getSystem(selectedCoordinateSystem)
|
||
: { id: "wgs84", label: "WGS84" };
|
||
const projected = system.id === "webmercator";
|
||
const unitSelect = document.getElementById("gridIntervalUnit");
|
||
const meterOption = unitSelect.querySelector('option[value="meter"]');
|
||
const angularOptions = Array.from(unitSelect.querySelectorAll('option:not([value="meter"])'));
|
||
if (gridConfig.projected !== projected) {
|
||
document.getElementById("gridInterval").value = "";
|
||
document.getElementById("gridIntervalEquivalent").textContent = "自动";
|
||
gridConfig.interval = 0;
|
||
gridConfig.projected = projected;
|
||
}
|
||
angularOptions.forEach((option) => {
|
||
option.disabled = projected;
|
||
option.hidden = projected;
|
||
});
|
||
meterOption.disabled = !projected;
|
||
meterOption.hidden = !projected;
|
||
if (projected) unitSelect.value = "meter";
|
||
else if (unitSelect.value === "meter") unitSelect.value = "degree";
|
||
document.getElementById("gridSystemHint").textContent = projected
|
||
? "当前:Web墨卡托 X/Y 米制网格。可手动输入米数;留空时自动计算。"
|
||
: "当前:" + system.label + " 经纬网格。可手动输入小数;留空时随缩放自动计算。";
|
||
document.getElementById("gridStartLonLabel").textContent = projected ? "起始 X(米)" : "起始经度";
|
||
document.getElementById("gridStartLatLabel").textContent = projected ? "起始 Y(米)" : "起始纬度";
|
||
if (map.hasLayer(gridLayer)) gridLayer.redraw();
|
||
};
|
||
|
||
const setGridVisibility = (visible) => {
|
||
document.body.classList.toggle("hide-map-grid", !visible);
|
||
if (visible) {
|
||
gridLayer.setOpacity(1);
|
||
if (!map.hasLayer(gridLayer)) map.addLayer(gridLayer);
|
||
gridLayer.redraw();
|
||
} else {
|
||
gridLayer.setOpacity(0);
|
||
if (map.hasLayer(gridLayer)) map.removeLayer(gridLayer);
|
||
if (gridLayer._container) gridLayer._container.style.display = "none";
|
||
}
|
||
};
|
||
|
||
|
||
const demCache = new Map();
|
||
const demTileData = new Map();
|
||
|
||
const loadTerrariumTile = (z, x, y) => {
|
||
const key = z + "/" + x + "/" + y;
|
||
if (demCache.has(key)) return demCache.get(key);
|
||
|
||
const promise = new Promise((resolve, reject) => {
|
||
const image = new Image();
|
||
image.crossOrigin = "anonymous";
|
||
image.onload = () => {
|
||
try {
|
||
const canvas = document.createElement("canvas");
|
||
canvas.width = 256;
|
||
canvas.height = 256;
|
||
const ctx = canvas.getContext("2d", { willReadFrequently: true });
|
||
ctx.drawImage(image, 0, 0);
|
||
const pixels = ctx.getImageData(0, 0, 256, 256).data;
|
||
const elevation = new Float32Array(256 * 256);
|
||
for (let i = 0, p = 0; i < elevation.length; i += 1, p += 4) {
|
||
elevation[i] = (pixels[p] * 256 + pixels[p + 1] + pixels[p + 2] / 256) - 32768;
|
||
}
|
||
demTileData.set(key, elevation);
|
||
resolve(elevation);
|
||
} catch (error) {
|
||
reject(error);
|
||
}
|
||
};
|
||
image.onerror = () => {
|
||
demCache.delete(key);
|
||
reject(new Error("DEM tile unavailable"));
|
||
};
|
||
image.src = mapServiceUrl("tiles/dem/" + z + "/" + x + "/" + y + ".png");
|
||
});
|
||
|
||
demCache.set(key, promise);
|
||
if (demCache.size > 240) {
|
||
const oldest = demCache.keys().next().value;
|
||
demCache.delete(oldest);
|
||
demTileData.delete(oldest);
|
||
}
|
||
return promise;
|
||
};
|
||
|
||
const TerrainGridLayer = L.GridLayer.extend({
|
||
initialize(options) {
|
||
L.GridLayer.prototype.initialize.call(this, options);
|
||
this.mode = options.mode || "contour";
|
||
},
|
||
|
||
createTile(coords, done) {
|
||
const tile = document.createElement("canvas");
|
||
tile.width = 256;
|
||
tile.height = 256;
|
||
this.renderTile(coords, tile)
|
||
.then(() => done(null, tile))
|
||
.catch(() => done(null, tile));
|
||
return tile;
|
||
},
|
||
|
||
async renderTile(coords, tile) {
|
||
const sourceZ = Math.max(9, Math.min(coords.z - (this.mode === "contour" ? 2 : 0), 13));
|
||
const scale = Math.pow(2, coords.z - sourceZ);
|
||
const sourceX = Math.floor(coords.x / scale);
|
||
const sourceY = Math.floor(coords.y / scale);
|
||
const cropSize = 256 / scale;
|
||
const cropX = (coords.x - sourceX * scale) * cropSize;
|
||
const cropY = (coords.y - sourceY * scale) * cropSize;
|
||
|
||
const source = await loadTerrariumTile(sourceZ, sourceX, sourceY);
|
||
const values = new Float64Array(256 * 256);
|
||
let min = Infinity;
|
||
let max = -Infinity;
|
||
|
||
for (let y = 0; y < 256; y += 1) {
|
||
const sy = Math.min(255, Math.max(0, Math.floor(cropY + (y + 0.5) * cropSize / 256)));
|
||
for (let x = 0; x < 256; x += 1) {
|
||
const sx = Math.min(255, Math.max(0, Math.floor(cropX + (x + 0.5) * cropSize / 256)));
|
||
const value = source[sy * 256 + sx];
|
||
values[y * 256 + x] = value;
|
||
if (value < min) min = value;
|
||
if (value > max) max = value;
|
||
}
|
||
}
|
||
|
||
if (this.mode === "contour") {
|
||
const smoothed = new Float64Array(values.length);
|
||
for (let y = 0; y < 256; y += 1) {
|
||
for (let x = 0; x < 256; x += 1) {
|
||
let total = 0;
|
||
let count = 0;
|
||
for (let oy = -2; oy <= 2; oy += 1) {
|
||
const sy = Math.max(0, Math.min(255, y + oy));
|
||
for (let ox = -2; ox <= 2; ox += 1) {
|
||
const sx = Math.max(0, Math.min(255, x + ox));
|
||
total += values[sy * 256 + sx];
|
||
count += 1;
|
||
}
|
||
}
|
||
smoothed[y * 256 + x] = total / count;
|
||
}
|
||
}
|
||
values.set(smoothed);
|
||
min = Infinity;
|
||
max = -Infinity;
|
||
for (let i = 0; i < values.length; i += 1) {
|
||
if (values[i] < min) min = values[i];
|
||
if (values[i] > max) max = values[i];
|
||
}
|
||
}
|
||
|
||
const ctx = tile.getContext("2d");
|
||
ctx.clearRect(0, 0, 256, 256);
|
||
|
||
if (this.mode === "hillshade") {
|
||
const image = ctx.createImageData(256, 256);
|
||
const pixels = image.data;
|
||
const range = Math.max(1, max - min);
|
||
for (let y = 0; y < 256; y += 1) {
|
||
for (let x = 0; x < 256; x += 1) {
|
||
const index = y * 256 + x;
|
||
const left = values[index - (x > 0 ? 1 : 0)];
|
||
const right = values[index + (x < 255 ? 1 : 0)];
|
||
const up = values[index - (y > 0 ? 256 : 0)];
|
||
const down = values[index + (y < 255 ? 256 : 0)];
|
||
const dzdx = (right - left) / Math.max(1, scale);
|
||
const dzdy = (down - up) / Math.max(1, scale);
|
||
const light = Math.max(0, Math.min(1, 0.62 + (-dzdx * 0.42 - dzdy * 0.32) / 28));
|
||
const elevation = Math.max(0, Math.min(1, (values[index] - min) / range));
|
||
const p = index * 4;
|
||
pixels[p] = Math.round((207 - 48 * elevation) * light);
|
||
pixels[p + 1] = Math.round((214 - 35 * elevation) * light);
|
||
pixels[p + 2] = Math.round((196 - 20 * elevation) * light);
|
||
pixels[p + 3] = 132;
|
||
}
|
||
}
|
||
ctx.putImageData(image, 0, 0);
|
||
return;
|
||
}
|
||
|
||
const northwest = map.unproject([coords.x * 256, coords.y * 256], coords.z);
|
||
const southeast = map.unproject([(coords.x + 1) * 256, (coords.y + 1) * 256], coords.z);
|
||
const latSpan = Math.abs(northwest.lat - southeast.lat);
|
||
const interval = contourConfig.interval === 0
|
||
? (coords.z <= 8 ? 500 : coords.z === 9 ? 200 : coords.z === 10 ? 100 : coords.z === 11 ? 50 : coords.z === 12 ? 20 : coords.z === 13 ? 10 : 5)
|
||
: contourConfig.interval;
|
||
const origin = contourConfig.startElevation;
|
||
const start = Math.ceil((min - origin) / interval) * interval + origin;
|
||
const thresholds = [];
|
||
for (let value = start; value <= max && thresholds.length < 32; value += interval) thresholds.push(value);
|
||
if (!thresholds.length) return;
|
||
|
||
const contours = d3.contours().size([256, 256]).thresholds(thresholds).smooth(true)(values);
|
||
ctx.lineJoin = "round";
|
||
ctx.lineCap = "round";
|
||
|
||
contours.forEach((contour) => {
|
||
const stepIndex = Math.round((contour.value - contourConfig.startElevation) / interval);
|
||
const major = contourConfig.boldEvery > 0 && Math.abs(stepIndex % contourConfig.boldEvery) === 0;
|
||
const baseColor = contourConfig.color;
|
||
ctx.beginPath();
|
||
contour.coordinates.forEach((polygon) => {
|
||
polygon.forEach((ring) => {
|
||
ring.forEach((point, index) => {
|
||
if (index === 0) ctx.moveTo(point[0], point[1]);
|
||
else ctx.lineTo(point[0], point[1]);
|
||
});
|
||
ctx.closePath();
|
||
});
|
||
});
|
||
ctx.strokeStyle = major ? baseColor : baseColor + "B5";
|
||
ctx.lineWidth = major ? contourConfig.boldWidth : contourConfig.width;
|
||
ctx.stroke();
|
||
|
||
const shouldLabel = major || (contourConfig.boldEvery === 0 && coords.z >= 12);
|
||
if (!shouldLabel) return;
|
||
|
||
contour.coordinates.forEach((polygon) => {
|
||
polygon.forEach((ring) => {
|
||
const spacing = coords.z >= 13 ? 110 : 160;
|
||
for (let index = Math.floor(spacing / 2); index < ring.length; index += spacing) {
|
||
const point = ring[index];
|
||
const previous = ring[Math.max(0, index - 2)];
|
||
const next = ring[Math.min(ring.length - 1, index + 2)];
|
||
let angle = Math.atan2(next[1] - previous[1], next[0] - previous[0]);
|
||
if (angle > Math.PI / 2) angle -= Math.PI;
|
||
if (angle < -Math.PI / 2) angle += Math.PI;
|
||
|
||
ctx.save();
|
||
ctx.translate(point[0], point[1]);
|
||
ctx.rotate(angle);
|
||
ctx.font = "bold 10px Inter, sans-serif";
|
||
ctx.textAlign = "center";
|
||
ctx.textBaseline = "middle";
|
||
ctx.lineWidth = 3;
|
||
ctx.strokeStyle = "rgba(255, 255, 255, 0.92)";
|
||
ctx.strokeText(String(Math.round(contour.value)), 0, -1);
|
||
ctx.fillStyle = baseColor;
|
||
ctx.fillText(String(Math.round(contour.value)), 0, -1);
|
||
ctx.restore();
|
||
}
|
||
});
|
||
});
|
||
});
|
||
}
|
||
});
|
||
|
||
|
||
const ContourOverlayLayer = L.Layer.extend({
|
||
|
||
onAdd(map) {
|
||
this._map = map;
|
||
this._canvas = document.createElement("canvas");
|
||
this._canvas.className = "contour-overlay-canvas";
|
||
this._canvas.setAttribute("aria-hidden", "true");
|
||
map.getContainer().appendChild(this._canvas);
|
||
this._draw();
|
||
this._onViewChange = () => this._draw();
|
||
map.on("moveend zoomend resize", this._onViewChange);
|
||
},
|
||
|
||
onRemove(map) {
|
||
map.off("moveend zoomend resize", this._onViewChange);
|
||
if (this._canvas) this._canvas.remove();
|
||
this._canvas = null;
|
||
},
|
||
|
||
redraw() {
|
||
this._draw();
|
||
},
|
||
|
||
async _draw() {
|
||
if (!this._map || !this._canvas) return;
|
||
this._drawId = (this._drawId || 0) + 1;
|
||
const drawId = this._drawId;
|
||
const map = this._map;
|
||
const canvas = this._canvas;
|
||
const rect = map.getContainer().getBoundingClientRect();
|
||
const dpr = Math.min(2, window.devicePixelRatio || 1);
|
||
canvas.width = Math.round(rect.width * dpr);
|
||
canvas.height = Math.round(rect.height * dpr);
|
||
canvas.style.width = rect.width + "px";
|
||
canvas.style.height = rect.height + "px";
|
||
|
||
const ctx = canvas.getContext("2d");
|
||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||
ctx.clearRect(0, 0, rect.width, rect.height);
|
||
|
||
const displayZoom = map.getZoom();
|
||
const sourceZ = Math.max(7, Math.min(10, Math.round(displayZoom) - 4));
|
||
const bounds = map.getBounds().pad(0.08);
|
||
const worldSize = 256 * Math.pow(2, sourceZ);
|
||
const nw = map.project(bounds.getNorthWest(), sourceZ);
|
||
const se = map.project(bounds.getSouthEast(), sourceZ);
|
||
const minTileX = Math.max(0, Math.floor(nw.x / 256));
|
||
const maxTileX = Math.min(Math.pow(2, sourceZ) - 1, Math.floor(se.x / 256));
|
||
const minTileY = Math.max(0, Math.floor(nw.y / 256));
|
||
const maxTileY = Math.min(Math.pow(2, sourceZ) - 1, Math.floor(se.y / 256));
|
||
const tileCount = (maxTileX - minTileX + 1) * (maxTileY - minTileY + 1);
|
||
if (!Number.isFinite(tileCount) || tileCount < 1 || tileCount > 36) return;
|
||
|
||
const tileData = await Promise.all(
|
||
Array.from({ length: maxTileY - minTileY + 1 }, (_, row) =>
|
||
Promise.all(
|
||
Array.from({ length: maxTileX - minTileX + 1 }, (_, col) =>
|
||
loadTerrariumTile(sourceZ, minTileX + col, minTileY + row)
|
||
)
|
||
)
|
||
)
|
||
);
|
||
if (drawId !== this._drawId || !this._canvas) return;
|
||
|
||
const width = (maxTileX - minTileX + 1) * 256;
|
||
const height = (maxTileY - minTileY + 1) * 256;
|
||
const values = new Float64Array(width * height);
|
||
for (let row = 0; row < tileData.length; row += 1) {
|
||
for (let col = 0; col < tileData[row].length; col += 1) {
|
||
const tileValues = tileData[row][col];
|
||
for (let y = 0; y < 256; y += 1) {
|
||
for (let x = 0; x < 256; x += 1) {
|
||
values[(row * 256 + y) * width + col * 256 + x] = tileValues[y * 256 + x];
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
const smoothed = new Float64Array(values.length);
|
||
for (let y = 0; y < height; y += 1) {
|
||
for (let x = 0; x < width; x += 1) {
|
||
let total = 0;
|
||
let count = 0;
|
||
for (let oy = -1; oy <= 1; oy += 1) {
|
||
const sy = Math.max(0, Math.min(height - 1, y + oy));
|
||
for (let ox = -1; ox <= 1; ox += 1) {
|
||
const sx = Math.max(0, Math.min(width - 1, x + ox));
|
||
total += values[sy * width + sx];
|
||
count += 1;
|
||
}
|
||
}
|
||
smoothed[y * width + x] = total / count;
|
||
}
|
||
}
|
||
|
||
let min = Infinity;
|
||
let max = -Infinity;
|
||
for (let i = 0; i < smoothed.length; i += 1) {
|
||
if (smoothed[i] < min) min = smoothed[i];
|
||
if (smoothed[i] > max) max = smoothed[i];
|
||
}
|
||
|
||
const interval = contourConfig.interval === 0
|
||
? (displayZoom <= 8 ? 500 : displayZoom === 9 ? 200 : displayZoom === 10 ? 100 : displayZoom === 11 ? 50 : displayZoom === 12 ? 20 : displayZoom === 13 ? 10 : 5)
|
||
: contourConfig.interval;
|
||
const origin = contourConfig.startElevation;
|
||
const start = Math.ceil((min - origin) / interval) * interval + origin;
|
||
const thresholds = [];
|
||
for (let value = start; value <= max && thresholds.length < 48; value += interval) thresholds.push(value);
|
||
if (!thresholds.length) return;
|
||
|
||
const contours = d3.contours().size([width, height]).thresholds(thresholds).smooth(true)(smoothed);
|
||
const pixelScale = Math.pow(2, displayZoom - sourceZ);
|
||
const pixelOrigin = map.getPixelBounds().min;
|
||
const pointFor = (gridX, gridY) => {
|
||
const worldX = minTileX * 256 + gridX;
|
||
const worldY = minTileY * 256 + gridY;
|
||
return {
|
||
x: worldX * pixelScale - pixelOrigin.x,
|
||
y: worldY * pixelScale - pixelOrigin.y
|
||
};
|
||
};
|
||
|
||
contours.forEach((contour) => {
|
||
const stepIndex = Math.round((contour.value - contourConfig.startElevation) / interval);
|
||
const major = contourConfig.boldEvery > 0 && Math.abs(stepIndex % contourConfig.boldEvery) === 0;
|
||
const baseColor = contourConfig.color;
|
||
ctx.beginPath();
|
||
contour.coordinates.forEach((polygon) => {
|
||
polygon.forEach((ring) => {
|
||
ring.forEach((point, index) => {
|
||
const projected = pointFor(point[0], point[1]);
|
||
if (index === 0) ctx.moveTo(projected.x, projected.y);
|
||
else ctx.lineTo(projected.x, projected.y);
|
||
});
|
||
ctx.closePath();
|
||
});
|
||
});
|
||
ctx.strokeStyle = major ? baseColor : baseColor + "B5";
|
||
ctx.lineWidth = major ? contourConfig.boldWidth : contourConfig.width;
|
||
ctx.stroke();
|
||
|
||
const shouldLabel = major || (contourConfig.boldEvery === 0 && displayZoom >= 12);
|
||
if (!shouldLabel) return;
|
||
contour.coordinates.forEach((polygon) => {
|
||
polygon.forEach((ring) => {
|
||
const spacing = displayZoom >= 13 ? 120 : 175;
|
||
for (let index = Math.floor(spacing / 2); index < ring.length; index += spacing) {
|
||
const point = pointFor(ring[index][0], ring[index][1]);
|
||
const previous = pointFor(ring[Math.max(0, index - 2)][0], ring[Math.max(0, index - 2)][1]);
|
||
const next = pointFor(ring[Math.min(ring.length - 1, index + 2)][0], ring[Math.min(ring.length - 1, index + 2)][1]);
|
||
let angle = Math.atan2(next.y - previous.y, next.x - previous.x);
|
||
if (angle > Math.PI / 2) angle -= Math.PI;
|
||
if (angle < -Math.PI / 2) angle += Math.PI;
|
||
ctx.save();
|
||
ctx.translate(point.x, point.y);
|
||
ctx.rotate(angle);
|
||
ctx.font = "bold 10px Inter, sans-serif";
|
||
ctx.textAlign = "center";
|
||
ctx.textBaseline = "middle";
|
||
ctx.lineWidth = 3;
|
||
ctx.strokeStyle = "rgba(255, 255, 255, 0.92)";
|
||
ctx.strokeText(String(Math.round(contour.value)), 0, -1);
|
||
ctx.fillStyle = baseColor;
|
||
ctx.fillText(String(Math.round(contour.value)), 0, -1);
|
||
ctx.restore();
|
||
}
|
||
});
|
||
});
|
||
});
|
||
}
|
||
});
|
||
const contourTerrainLayer = new ContourOverlayLayer({
|
||
zIndex: 350,
|
||
attribution: "Contours: AWS Terrain Tiles, generated in browser"
|
||
});
|
||
|
||
const hillshadeTerrainLayer = new TerrainGridLayer({
|
||
mode: "hillshade",
|
||
zIndex: 445,
|
||
attribution: "Hillshade: AWS Terrain Tiles, generated in browser"
|
||
});
|
||
|
||
|
||
const interpolatePathForProfile = (latlngs, sampleCount) => {
|
||
const segmentLengths = [];
|
||
let totalLength = 0;
|
||
for (let i = 1; i < latlngs.length; i += 1) {
|
||
const length = haversineDistance(latlngs[i - 1], latlngs[i]);
|
||
segmentLengths.push(length);
|
||
totalLength += length;
|
||
}
|
||
const points = [];
|
||
for (let sample = 0; sample <= sampleCount; sample += 1) {
|
||
const target = totalLength * sample / sampleCount;
|
||
let walked = 0;
|
||
let segmentIndex = 0;
|
||
while (segmentIndex < segmentLengths.length - 1 && walked + segmentLengths[segmentIndex] < target) {
|
||
walked += segmentLengths[segmentIndex];
|
||
segmentIndex += 1;
|
||
}
|
||
const ratio = segmentLengths[segmentIndex] ? (target - walked) / segmentLengths[segmentIndex] : 0;
|
||
const start = latlngs[segmentIndex];
|
||
const end = latlngs[segmentIndex + 1] || start;
|
||
points.push(L.latLng(
|
||
start.lat + (end.lat - start.lat) * ratio,
|
||
start.lng + (end.lng - start.lng) * ratio
|
||
));
|
||
}
|
||
return { points, totalLength };
|
||
};
|
||
|
||
const formatLatLng = (latlng) => coordinateSystems
|
||
? coordinateSystems.format(latlng.lat, latlng.lng, selectedCoordinateSystem, {
|
||
includeSystem: true,
|
||
precision: 5
|
||
})
|
||
: latlng.lat.toFixed(5) + ", " + latlng.lng.toFixed(5);
|
||
|
||
const drawPathProfile = (canvas, profile) => {
|
||
if (!canvas || !profile || !profile.samples || profile.samples.length < 2) return;
|
||
const cssWidth = Math.max(220, canvas.clientWidth || canvas.parentElement?.clientWidth || 300);
|
||
const cssHeight = 138;
|
||
const dpr = Math.min(2, window.devicePixelRatio || 1);
|
||
canvas.width = Math.round(cssWidth * dpr);
|
||
canvas.height = Math.round(cssHeight * dpr);
|
||
canvas.style.height = cssHeight + "px";
|
||
|
||
const ctx = canvas.getContext("2d");
|
||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||
const width = cssWidth;
|
||
const height = cssHeight;
|
||
ctx.clearRect(0, 0, width, height);
|
||
ctx.fillStyle = "#f7f9f6";
|
||
ctx.fillRect(0, 0, width, height);
|
||
|
||
const elevations = profile.samples;
|
||
const min = Math.min(...elevations);
|
||
const max = Math.max(...elevations);
|
||
const range = Math.max(1, max - min);
|
||
const plotLeft = 34;
|
||
const plotRight = width - 8;
|
||
const plotTop = 12;
|
||
const plotBottom = height - 28;
|
||
const yFor = (value) => plotTop + (plotBottom - plotTop) * (1 - (value - min) / range);
|
||
const xForDistance = (distance) =>
|
||
plotLeft + (plotRight - plotLeft) * Math.max(0, Math.min(1, distance / Math.max(1, profile.totalLength)));
|
||
|
||
ctx.strokeStyle = "#dfe5df";
|
||
ctx.lineWidth = 1;
|
||
for (let index = 1; index < 4; index += 1) {
|
||
const y = plotTop + (plotBottom - plotTop) * index / 4;
|
||
ctx.beginPath();
|
||
ctx.moveTo(plotLeft, y);
|
||
ctx.lineTo(plotRight, y);
|
||
ctx.stroke();
|
||
}
|
||
|
||
ctx.beginPath();
|
||
elevations.forEach((value, index) => {
|
||
const x = plotLeft + (plotRight - plotLeft) * index / (elevations.length - 1);
|
||
const y = yFor(value);
|
||
if (index === 0) ctx.moveTo(x, y);
|
||
else ctx.lineTo(x, y);
|
||
});
|
||
ctx.lineTo(plotRight, plotBottom);
|
||
ctx.lineTo(plotLeft, plotBottom);
|
||
ctx.closePath();
|
||
ctx.fillStyle = "rgba(32, 92, 70, 0.13)";
|
||
ctx.fill();
|
||
|
||
ctx.beginPath();
|
||
elevations.forEach((value, index) => {
|
||
const x = plotLeft + (plotRight - plotLeft) * index / (elevations.length - 1);
|
||
const y = yFor(value);
|
||
if (index === 0) ctx.moveTo(x, y);
|
||
else ctx.lineTo(x, y);
|
||
});
|
||
ctx.strokeStyle = "#205c46";
|
||
ctx.lineWidth = 1.8;
|
||
ctx.stroke();
|
||
|
||
(profile.nodes || []).forEach((node, index) => {
|
||
const x = xForDistance(node.distance);
|
||
const y = yFor(node.elevation);
|
||
ctx.beginPath();
|
||
ctx.arc(x, y, 3.4, 0, Math.PI * 2);
|
||
ctx.fillStyle = "#ffffff";
|
||
ctx.fill();
|
||
ctx.lineWidth = 1.5;
|
||
ctx.strokeStyle = "#205c46";
|
||
ctx.stroke();
|
||
if (profile.nodes.length <= 10) {
|
||
ctx.fillStyle = "#205c46";
|
||
ctx.font = "bold 8px Inter, sans-serif";
|
||
ctx.textAlign = "center";
|
||
ctx.fillText(String(index + 1), x, y - 6);
|
||
}
|
||
});
|
||
|
||
ctx.fillStyle = "#68736c";
|
||
ctx.font = "10px Inter, sans-serif";
|
||
ctx.textAlign = "right";
|
||
ctx.fillText(max.toFixed(0), 30, yFor(max) + 3);
|
||
ctx.fillText(min.toFixed(0), 30, yFor(min) + 3);
|
||
ctx.textAlign = "left";
|
||
ctx.fillText("0", plotLeft, height - 7);
|
||
ctx.textAlign = "right";
|
||
ctx.fillText(formatDistance(profile.totalLength), plotRight, height - 7);
|
||
};
|
||
|
||
const analyzePathProfile = async (item, directDistance) => {
|
||
const latlngs = item.points;
|
||
item.profile = { status: "loading" };
|
||
renderDrawingList();
|
||
const nodeDistances = [];
|
||
let travelled = 0;
|
||
latlngs.forEach((point, index) => {
|
||
if (index > 0) travelled += haversineDistance(latlngs[index - 1], point);
|
||
nodeDistances.push(travelled);
|
||
});
|
||
|
||
try {
|
||
const sampleCount = Math.min(160, Math.max(40, latlngs.length * 16));
|
||
const sampled = interpolatePathForProfile(latlngs, sampleCount);
|
||
|
||
const [samples, nodeElevations] = await Promise.all([
|
||
Promise.all(sampled.points.map(getElevationAt)),
|
||
Promise.all(latlngs.map(getElevationAt))
|
||
]);
|
||
if (
|
||
samples.some((value) => value === null || !Number.isFinite(value)) ||
|
||
nodeElevations.some((value) => value === null || !Number.isFinite(value))
|
||
) {
|
||
throw new Error("DEM data unavailable");
|
||
}
|
||
|
||
const min = Math.min(...samples);
|
||
const max = Math.max(...samples);
|
||
const gain = samples.reduce((sum, value, index) =>
|
||
index ? sum + Math.max(0, value - samples[index - 1]) : 0, 0);
|
||
const nodes = latlngs.map((point, index) => ({
|
||
lat: point.lat,
|
||
lng: point.lng,
|
||
elevation: nodeElevations[index],
|
||
distance: nodeDistances[index]
|
||
}));
|
||
|
||
item.profile = {
|
||
status: "ready",
|
||
samples,
|
||
nodes,
|
||
totalLength: sampled.totalLength,
|
||
directDistance,
|
||
min,
|
||
max,
|
||
gain
|
||
};
|
||
item.detail =
|
||
"总长 " + formatDistance(sampled.totalLength) +
|
||
" · " + nodes.length + " 个节点" +
|
||
" · 最高 " + max.toFixed(0) + " m" +
|
||
" · 爬升 " + gain.toFixed(0) + " m";
|
||
|
||
nodes.forEach((node, index) => {
|
||
if (!(item.layer instanceof L.LayerGroup)) return;
|
||
item.layer.addLayer(
|
||
L.circleMarker([node.lat, node.lng], {
|
||
radius: 4.5,
|
||
color: "#ffffff",
|
||
weight: 1.7,
|
||
fillColor: "#245da8",
|
||
fillOpacity: 1
|
||
}).bindPopup(() =>
|
||
"<strong>路径节点 " + (index + 1) + "</strong>" +
|
||
"<br>位置:" + formatLatLng(node) +
|
||
"<br>高程:" + node.elevation.toFixed(1) + " m" +
|
||
"<br>里程:" + formatDistance(node.distance)
|
||
)
|
||
);
|
||
});
|
||
applyDrawingStyle(item);
|
||
} catch (error) {
|
||
item.profile = {
|
||
status: "error",
|
||
nodes: latlngs.map((point, index) => ({
|
||
lat: point.lat,
|
||
lng: point.lng,
|
||
elevation: null,
|
||
distance: nodeDistances[index]
|
||
}))
|
||
};
|
||
item.detail += " · 高程读取失败";
|
||
}
|
||
|
||
renderDrawingList();
|
||
scheduleDrawingSave();
|
||
const row = drawingList.querySelector('[data-drawing-id="' + item.id + '"]');
|
||
if (row && item.profile.status === "ready") {
|
||
window.requestAnimationFrame(() => drawPathProfile(row.querySelector(".profile-canvas"), item.profile));
|
||
}
|
||
};
|
||
const drawingGroup = L.layerGroup().addTo(map);
|
||
const drawingStatus = document.getElementById("drawingStatus");
|
||
const drawingList = document.getElementById("drawingList");
|
||
const drawingItems = [];
|
||
const drawingCounts = { path: 0, range: 0, viewshed: 0, observation: 0 };
|
||
let drawingMode = null;
|
||
let drawingPoints = [];
|
||
let temporaryShape = null;
|
||
let viewshedStart = null;
|
||
let visibilityTask = 0;
|
||
let drawingGeneration = 0;
|
||
|
||
const defaultDrawingColor = (type, data = {}) => {
|
||
if (type === "path") return "#245da8";
|
||
if (type === "range") return "#205c46";
|
||
if (type === "viewshed") {
|
||
return data.viewshed?.analysis?.visible === false ? "#c64a3b" : "#1f9d62";
|
||
}
|
||
return "#315a47";
|
||
};
|
||
|
||
const applyDrawingStyle = (item) => {
|
||
if (!item?.layer) return;
|
||
const opacity = Math.max(0, Math.min(1, Number(item.opacity ?? 1)));
|
||
const color = item.color || defaultDrawingColor(item.type, item);
|
||
const visit = (layer) => {
|
||
if (!layer) return;
|
||
if (layer instanceof L.CircleMarker) {
|
||
layer.setStyle({ color, opacity, fillColor: color, fillOpacity: opacity });
|
||
} else if (layer instanceof L.Polygon) {
|
||
layer.setStyle({ color, opacity, fillColor: color, fillOpacity: 0.16 * opacity });
|
||
} else if (layer instanceof L.Polyline) {
|
||
layer.setStyle({ color, opacity: 0.95 * opacity });
|
||
} else if (typeof layer.setColors === "function" && typeof layer.setOpacity === "function") {
|
||
if (item.customColor) {
|
||
layer.setColors({ near: color, mid: color, far: color });
|
||
}
|
||
layer.setOpacity(0.62 * opacity);
|
||
}
|
||
if (typeof layer.eachLayer === "function") {
|
||
layer.eachLayer(visit);
|
||
}
|
||
};
|
||
visit(item.layer);
|
||
};
|
||
|
||
const setDrawingVisibility = (item, visible, options = {}) => {
|
||
item.visible = Boolean(visible);
|
||
if (item.visible) drawingGroup.addLayer(item.layer);
|
||
else drawingGroup.removeLayer(item.layer);
|
||
if (options.save !== false) scheduleDrawingSave();
|
||
};
|
||
|
||
const formatDistance = (meters) => meters < 1000
|
||
? Math.round(meters) + " m"
|
||
: (meters / 1000).toFixed(meters < 10000 ? 2 : 1) + " km";
|
||
|
||
const formatArea = (squareMeters) => squareMeters < 1000000
|
||
? Math.round(squareMeters).toLocaleString("zh-CN") + " m²"
|
||
: (squareMeters / 1000000).toFixed(2) + " km²";
|
||
|
||
const haversineDistance = (a, b) => {
|
||
const radius = 6371008.8;
|
||
const toRad = (value) => value * Math.PI / 180;
|
||
const dLat = toRad(b.lat - a.lat);
|
||
const dLon = toRad(b.lng - a.lng);
|
||
const lat1 = toRad(a.lat);
|
||
const lat2 = toRad(b.lat);
|
||
const h = Math.sin(dLat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;
|
||
return radius * 2 * Math.atan2(Math.sqrt(h), Math.sqrt(1 - h));
|
||
};
|
||
|
||
const sphericalPolygonArea = (points) => {
|
||
if (points.length < 3) return 0;
|
||
const radius = 6378137;
|
||
let total = 0;
|
||
for (let i = 0; i < points.length; i += 1) {
|
||
const current = points[i];
|
||
const next = points[(i + 1) % points.length];
|
||
total += (toRadians(next.lng) - toRadians(current.lng)) *
|
||
(2 + Math.sin(toRadians(current.lat)) + Math.sin(toRadians(next.lat)));
|
||
}
|
||
return Math.abs(total * radius * radius / 2);
|
||
};
|
||
|
||
function toRadians(value) {
|
||
return value * Math.PI / 180;
|
||
}
|
||
|
||
const getElevationAt = async (latlng) => {
|
||
const z = 12;
|
||
const scale = 256 * Math.pow(2, z);
|
||
const worldX = (latlng.lng + 180) / 360 * scale;
|
||
const latRad = toRadians(latlng.lat);
|
||
const worldY = (1 - Math.log(Math.tan(latRad) + 1 / Math.cos(latRad)) / Math.PI) / 2 * scale;
|
||
const tileX = Math.floor(worldX / 256);
|
||
const tileY = Math.floor(worldY / 256);
|
||
const pixelX = Math.max(0, Math.min(255, Math.floor(worldX - tileX * 256)));
|
||
const pixelY = Math.max(0, Math.min(255, Math.floor(worldY - tileY * 256)));
|
||
const values = await loadTerrariumTile(z, tileX, tileY);
|
||
return values[pixelY * 256 + pixelX];
|
||
};
|
||
|
||
const latLngToTilePosition = (latlng, z) => {
|
||
const scale = 256 * Math.pow(2, z);
|
||
const worldX = (latlng.lng + 180) / 360 * scale;
|
||
const latRad = toRadians(latlng.lat);
|
||
const worldY = (1 - Math.log(Math.tan(latRad) + 1 / Math.cos(latRad)) / Math.PI) / 2 * scale;
|
||
const tileX = Math.floor(worldX / 256);
|
||
const tileY = Math.floor(worldY / 256);
|
||
return {
|
||
key: z + "/" + tileX + "/" + tileY,
|
||
pixelX: Math.max(0, Math.min(255, Math.floor(worldX - tileX * 256))),
|
||
pixelY: Math.max(0, Math.min(255, Math.floor(worldY - tileY * 256)))
|
||
};
|
||
};
|
||
|
||
const elevationAtLoadedTile = (latlng, zoom = 12, smoothRadius = 0) => {
|
||
const position = latLngToTilePosition(latlng, zoom);
|
||
const values = demTileData.get(position.key);
|
||
if (!values) return null;
|
||
if (!smoothRadius) return values[position.pixelY * 256 + position.pixelX];
|
||
let total = 0;
|
||
let count = 0;
|
||
for (let offsetY = -smoothRadius; offsetY <= smoothRadius; offsetY += 1) {
|
||
const y = Math.max(0, Math.min(255, position.pixelY + offsetY));
|
||
for (let offsetX = -smoothRadius; offsetX <= smoothRadius; offsetX += 1) {
|
||
const x = Math.max(0, Math.min(255, position.pixelX + offsetX));
|
||
total += values[y * 256 + x];
|
||
count += 1;
|
||
}
|
||
}
|
||
return total / count;
|
||
};
|
||
|
||
const ensureDemTilesForBounds = async (bounds, zoom = 12) => {
|
||
const nw = map.project(bounds.getNorthWest(), zoom);
|
||
const se = map.project(bounds.getSouthEast(), zoom);
|
||
const maxTile = Math.pow(2, zoom) - 1;
|
||
const minX = Math.max(0, Math.floor(nw.x / 256));
|
||
const maxX = Math.min(maxTile, Math.floor(se.x / 256));
|
||
const minY = Math.max(0, Math.floor(nw.y / 256));
|
||
const maxY = Math.min(maxTile, Math.floor(se.y / 256));
|
||
const requests = [];
|
||
for (let y = minY; y <= maxY; y += 1) {
|
||
for (let x = minX; x <= maxX; x += 1) {
|
||
requests.push(loadTerrariumTile(zoom, x, y));
|
||
}
|
||
}
|
||
await Promise.all(requests);
|
||
};
|
||
|
||
const destinationPoint = (origin, bearing, distance) => {
|
||
const earthRadius = 6371008.8;
|
||
const angularDistance = distance / earthRadius;
|
||
const lat1 = toRadians(origin.lat);
|
||
const lon1 = toRadians(origin.lng);
|
||
const lat2 = Math.asin(
|
||
Math.sin(lat1) * Math.cos(angularDistance) +
|
||
Math.cos(lat1) * Math.sin(angularDistance) * Math.cos(bearing)
|
||
);
|
||
const lon2 = lon1 + Math.atan2(
|
||
Math.sin(bearing) * Math.sin(angularDistance) * Math.cos(lat1),
|
||
Math.cos(angularDistance) - Math.sin(lat1) * Math.sin(lat2)
|
||
);
|
||
return L.latLng(lat2 * 180 / Math.PI, ((lon2 * 180 / Math.PI + 540) % 360) - 180);
|
||
};
|
||
|
||
const VisibilityAreaLayer = L.Layer.extend({
|
||
initialize(cells, colors, opacity = 0.62) {
|
||
this._cells = cells || [];
|
||
this._colors = colors;
|
||
this._opacity = Math.max(0, Math.min(1, Number(opacity) || 0.62));
|
||
this.setColors(colors || { near: "#1f9d62", mid: "#54ad55", far: "#94bd4c" });
|
||
},
|
||
|
||
onAdd(map) {
|
||
this._map = map;
|
||
this._canvas = document.createElement("canvas");
|
||
this._canvas.className = "visibility-area-canvas";
|
||
this._canvas.setAttribute("aria-hidden", "true");
|
||
map.getContainer().appendChild(this._canvas);
|
||
this._redraw = this._redraw.bind(this);
|
||
map.on("moveend zoomend resize", this._redraw);
|
||
this._redraw();
|
||
},
|
||
|
||
onRemove(map) {
|
||
map.off("moveend zoomend resize", this._redraw);
|
||
if (this._canvas) this._canvas.remove();
|
||
this._canvas = null;
|
||
},
|
||
|
||
setColors(colors) {
|
||
this._colors = colors;
|
||
this._cells.forEach((cell) => {
|
||
cell.color = cell.ratio < 1 / 3
|
||
? colors.near
|
||
: cell.ratio < 2 / 3
|
||
? colors.mid
|
||
: colors.far;
|
||
});
|
||
if (this._map) this._redraw();
|
||
},
|
||
|
||
setOpacity(opacity) {
|
||
this._opacity = Math.max(0, Math.min(1, Number(opacity)));
|
||
if (this._map) this._redraw();
|
||
},
|
||
|
||
_redraw() {
|
||
if (!this._map || !this._canvas) return;
|
||
const rect = this._map.getContainer().getBoundingClientRect();
|
||
const dpr = Math.min(2, window.devicePixelRatio || 1);
|
||
this._canvas.width = Math.round(rect.width * dpr);
|
||
this._canvas.height = Math.round(rect.height * dpr);
|
||
this._canvas.style.width = rect.width + "px";
|
||
this._canvas.style.height = rect.height + "px";
|
||
|
||
const ctx = this._canvas.getContext("2d");
|
||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||
ctx.clearRect(0, 0, rect.width, rect.height);
|
||
const visibleBounds = this._map.getBounds().pad(0.04);
|
||
const groupedPaths = new Map();
|
||
|
||
this._cells.forEach((cell) => {
|
||
if (!visibleBounds.contains(cell.center)) return;
|
||
const projected = cell.points.map((point) => this._map.latLngToContainerPoint(point));
|
||
if (
|
||
projected.every((point) => point.x < -20) ||
|
||
projected.every((point) => point.x > rect.width + 20) ||
|
||
projected.every((point) => point.y < -20) ||
|
||
projected.every((point) => point.y > rect.height + 20)
|
||
) return;
|
||
|
||
let path = groupedPaths.get(cell.color);
|
||
if (!path) {
|
||
path = new Path2D();
|
||
groupedPaths.set(cell.color, path);
|
||
}
|
||
path.moveTo(projected[0].x, projected[0].y);
|
||
path.lineTo(projected[1].x, projected[1].y);
|
||
path.lineTo(projected[2].x, projected[2].y);
|
||
path.lineTo(projected[3].x, projected[3].y);
|
||
path.closePath();
|
||
});
|
||
|
||
ctx.globalAlpha = this._opacity;
|
||
groupedPaths.forEach((path, color) => {
|
||
ctx.fillStyle = color;
|
||
ctx.fill(path);
|
||
});
|
||
ctx.globalAlpha = 1;
|
||
}
|
||
});
|
||
|
||
const analyzeVisibilityArea = async (center, options = {}) => {
|
||
const existingItem = options.existingItem || null;
|
||
const config = options.config || {};
|
||
const runId = existingItem ? null : visibilityTask;
|
||
const innerRadiusInput = Number(
|
||
config.innerRadius ?? document.getElementById("visibilityInnerRadius").value
|
||
);
|
||
const outerRadiusInput = Number(
|
||
config.outerRadius ?? document.getElementById("visibilityOuterRadius").value
|
||
);
|
||
const sightHeightInput = Number(
|
||
config.sightHeight ?? document.getElementById("viewshedHeight").value
|
||
);
|
||
const innerRadius = Number.isFinite(innerRadiusInput)
|
||
? Math.max(0, Math.min(19999, innerRadiusInput))
|
||
: 0;
|
||
const outerRadius = Number.isFinite(outerRadiusInput)
|
||
? Math.max(1, Math.min(20000, outerRadiusInput))
|
||
: 1000;
|
||
const sightHeight = Number.isFinite(sightHeightInput)
|
||
? Math.max(0, Math.min(100, sightHeightInput))
|
||
: 1;
|
||
|
||
if (outerRadius <= innerRadius) {
|
||
updateDrawingStatus("外半径必须大于内半径。");
|
||
showToast("通视观察半径无效:外半径需要大于内半径。", "error");
|
||
return;
|
||
}
|
||
|
||
const colors = config.colorBands || {
|
||
near: document.getElementById("visibilityNearColor").value,
|
||
mid: document.getElementById("visibilityMidColor").value,
|
||
far: document.getElementById("visibilityFarColor").value
|
||
};
|
||
if (!options.silent) {
|
||
updateDrawingStatus("正在加载地形并计算周围可见范围…");
|
||
setStatus("正在计算通视范围…", "busy");
|
||
}
|
||
|
||
try {
|
||
const north = destinationPoint(center, 0, outerRadius);
|
||
const south = destinationPoint(center, Math.PI, outerRadius);
|
||
const east = destinationPoint(center, Math.PI / 2, outerRadius);
|
||
const west = destinationPoint(center, -Math.PI / 2, outerRadius);
|
||
const bounds = L.latLngBounds([south, west], [north, east]);
|
||
const demZoom = outerRadius <= 500 ? 14 : outerRadius <= 2500 ? 13 : 12;
|
||
await ensureDemTilesForBounds(bounds, demZoom);
|
||
if (runId !== null && runId !== visibilityTask) return;
|
||
|
||
const observerGround = elevationAtLoadedTile(center, demZoom, 1);
|
||
if (!Number.isFinite(observerGround)) throw new Error("Observer elevation unavailable");
|
||
const observerEye = observerGround + sightHeight;
|
||
const groundResolution = 156543.03392 * Math.cos(toRadians(center.lat)) / Math.pow(2, demZoom);
|
||
const radialStep = Math.max(8, Math.min(120, Math.max(outerRadius / 140, groundResolution * 1.5)));
|
||
const angleCount = Math.max(90, Math.min(360, Math.ceil(2 * Math.PI * outerRadius / radialStep)));
|
||
const halfAngle = Math.PI / angleCount;
|
||
const earthRadius = 6371008.8;
|
||
const cells = [];
|
||
let sampledTargets = 0;
|
||
let visibleTargets = 0;
|
||
|
||
for (let angleIndex = 0; angleIndex < angleCount; angleIndex += 1) {
|
||
const bearing = 2 * Math.PI * angleIndex / angleCount;
|
||
const rayDistances = [];
|
||
const rayGround = [];
|
||
const rayPoints = [];
|
||
for (let distance = radialStep / 2; distance <= outerRadius; distance += radialStep) {
|
||
const point = destinationPoint(center, bearing, distance);
|
||
const ground = elevationAtLoadedTile(point, demZoom, 1);
|
||
if (!Number.isFinite(ground)) continue;
|
||
const curvatureDrop = distance * distance / (2 * earthRadius);
|
||
rayDistances.push(distance);
|
||
rayGround.push(ground - curvatureDrop);
|
||
rayPoints.push(point);
|
||
}
|
||
|
||
for (let targetIndex = 0; targetIndex < rayDistances.length; targetIndex += 1) {
|
||
const distance = rayDistances[targetIndex];
|
||
if (distance < innerRadius) continue;
|
||
sampledTargets += 1;
|
||
const targetGround = rayGround[targetIndex];
|
||
let visible = true;
|
||
for (let sampleIndex = 0; sampleIndex < targetIndex; sampleIndex += 1) {
|
||
const ratio = rayDistances[sampleIndex] / distance;
|
||
const sightline = observerEye + (targetGround - observerEye) * ratio;
|
||
if (rayGround[sampleIndex] > sightline + 0.5) {
|
||
visible = false;
|
||
break;
|
||
}
|
||
}
|
||
if (!visible) continue;
|
||
visibleTargets += 1;
|
||
|
||
const innerDistance = Math.max(innerRadius, distance - radialStep / 2);
|
||
const outerDistance = Math.min(outerRadius, distance + radialStep / 2);
|
||
const ratio = (distance - innerRadius) / Math.max(1, outerRadius - innerRadius);
|
||
const color = ratio < 1 / 3 ? colors.near : ratio < 2 / 3 ? colors.mid : colors.far;
|
||
cells.push({
|
||
color,
|
||
ratio,
|
||
center: rayPoints[targetIndex],
|
||
points: [
|
||
destinationPoint(center, bearing - halfAngle, innerDistance),
|
||
destinationPoint(center, bearing + halfAngle, innerDistance),
|
||
destinationPoint(center, bearing + halfAngle, outerDistance),
|
||
destinationPoint(center, bearing - halfAngle, outerDistance)
|
||
]
|
||
});
|
||
}
|
||
}
|
||
|
||
if (runId !== null && runId !== visibilityTask) return;
|
||
if (!sampledTargets) throw new Error("No valid terrain samples");
|
||
|
||
const areaLayer = new VisibilityAreaLayer(cells, colors);
|
||
const rings = [
|
||
L.circle(center, {
|
||
radius: outerRadius,
|
||
color: "#315a47",
|
||
weight: 1.2,
|
||
dashArray: "6 5",
|
||
fill: false,
|
||
interactive: false
|
||
})
|
||
];
|
||
if (innerRadius > 0) {
|
||
rings.push(L.circle(center, {
|
||
radius: innerRadius,
|
||
color: "#315a47",
|
||
weight: 1,
|
||
dashArray: "3 5",
|
||
fill: false,
|
||
interactive: false
|
||
}));
|
||
}
|
||
const observer = L.circleMarker(center, {
|
||
radius: 7,
|
||
color: "#ffffff",
|
||
weight: 2.4,
|
||
fillColor: "#174c38",
|
||
fillOpacity: 1
|
||
}).bindPopup(() =>
|
||
"<strong>通视观察点</strong>" +
|
||
"<br>位置:" + formatLatLng(center) +
|
||
"<br>地面高程:" + observerGround.toFixed(1) + " m" +
|
||
"<br>视线高度:" + sightHeight.toFixed(1) + " m" +
|
||
"<br>观察环:" + formatDistance(innerRadius) + " – " + formatDistance(outerRadius)
|
||
);
|
||
const group = L.layerGroup([areaLayer, ...rings, observer]);
|
||
const visiblePercent = visibleTargets / sampledTargets * 100;
|
||
const detail =
|
||
"可见 " + visiblePercent.toFixed(1) + "%" +
|
||
" · 半径 " + formatDistance(innerRadius) + "–" + formatDistance(outerRadius) +
|
||
" · 视点 " + (observerGround + sightHeight).toFixed(1) + " m" +
|
||
"(地面 " + observerGround.toFixed(1) + " m" +
|
||
" + 视线高 " + sightHeight.toFixed(1) + " m)";
|
||
const observation = {
|
||
center: pointRecord(center),
|
||
innerRadius,
|
||
outerRadius,
|
||
sightHeight,
|
||
colorBands: { ...colors },
|
||
observerGround,
|
||
visiblePercent,
|
||
visibleTargets,
|
||
sampledTargets
|
||
};
|
||
|
||
if (existingItem) {
|
||
if (!drawingItems.includes(existingItem)) return;
|
||
drawingGroup.removeLayer(existingItem.layer);
|
||
existingItem.layer = group;
|
||
existingItem.detail = detail;
|
||
existingItem.observation = observation;
|
||
existingItem.areaLayer = areaLayer;
|
||
existingItem.colorBands = { ...colors };
|
||
drawingGroup.addLayer(group);
|
||
applyDrawingStyle(existingItem);
|
||
renderDrawingList();
|
||
scheduleDrawingSave();
|
||
} else {
|
||
addDrawingItem("observation", group, detail, {
|
||
areaLayer,
|
||
colorBands: { ...colors },
|
||
observation
|
||
});
|
||
}
|
||
|
||
if (!options.silent) {
|
||
updateDrawingStatus(
|
||
"通视观察完成:观察点地面 " + observerGround.toFixed(1) + " m,视线高度 " + sightHeight.toFixed(1) +
|
||
" m,视点高程 " + (observerGround + sightHeight).toFixed(1) + " m;内半径 " + formatDistance(innerRadius) +
|
||
",外半径 " + formatDistance(outerRadius) +
|
||
",约 " + visiblePercent.toFixed(1) + "% 的地表可见。"
|
||
);
|
||
setStatus("地图已就绪");
|
||
showToast("通视观察完成,可见范围已按距离着色。");
|
||
clearDrawingState();
|
||
}
|
||
} catch (error) {
|
||
if (runId !== null && runId !== visibilityTask) return;
|
||
if (existingItem) {
|
||
if (drawingItems.includes(existingItem)) {
|
||
existingItem.detail += " · 恢复失败,可重新计算";
|
||
renderDrawingList();
|
||
scheduleDrawingSave();
|
||
}
|
||
} else if (!options.silent) {
|
||
updateDrawingStatus("通视观察失败:地形数据加载失败,请稍后重试。");
|
||
setStatus("通视观察失败", "error");
|
||
showToast("地形数据加载失败,无法完成周围通视观察。", "error");
|
||
clearDrawingState();
|
||
}
|
||
}
|
||
};
|
||
|
||
const setTerrainFeatureOptionsVisibility = (visible) => {
|
||
const options = document.getElementById("terrainFeatureOptions");
|
||
options.hidden = !visible;
|
||
if (!visible) options.open = false;
|
||
};
|
||
|
||
const updateLegendVisibility = () => {
|
||
const master = document.getElementById("terrainFeatureToggle").checked;
|
||
const localVectorOn = document.getElementById("localVectorToggle").checked;
|
||
const localGroupChecked = (group) => localVectorOn && Boolean(
|
||
document.querySelector('.local-vector-layer-toggle[value="' + group + '"]:checked')
|
||
);
|
||
const visibility = {
|
||
railway: document.getElementById("railTileToggle").checked,
|
||
national: document.getElementById("nationalRailToggle").checked,
|
||
metro: document.getElementById("metroToggle").checked,
|
||
hillshade: document.getElementById("hillshadeToggle").checked,
|
||
grid: document.getElementById("gridToggle").checked,
|
||
contour: document.getElementById("contourToggle").checked,
|
||
"terrain-peak": master && document.getElementById("terrainPeakToggle").checked,
|
||
"terrain-valley": master && document.getElementById("terrainValleyToggle").checked,
|
||
boundary: document.getElementById("tdtBoundaryToggle").checked,
|
||
"local-roads": localGroupChecked("roads"),
|
||
"local-railways": localGroupChecked("railways"),
|
||
"local-water": localGroupChecked("water"),
|
||
"local-administration": localGroupChecked("administration"),
|
||
"local-province": localGroupChecked("province"),
|
||
"local-city": localGroupChecked("city"),
|
||
"local-county": localGroupChecked("county"),
|
||
"local-settlements": localGroupChecked("settlements"),
|
||
"local-vegetation": localGroupChecked("vegetation"),
|
||
"local-terrain": localGroupChecked("terrain"),
|
||
"local-facilities": localGroupChecked("facilities"),
|
||
"local-heritage": localGroupChecked("heritage"),
|
||
water: document.getElementById("waterToggle").checked,
|
||
port: document.getElementById("portToggle").checked,
|
||
vegetation: document.getElementById("vegetationToggle").checked,
|
||
viewshed: drawingItems.some((item) => item.type === "observation" && item.visible !== false)
|
||
};
|
||
document.querySelectorAll("[data-map-legend], [data-print-legend]").forEach((row) => {
|
||
const key = row.dataset.mapLegend || row.dataset.printLegend;
|
||
row.hidden = !visibility[key];
|
||
});
|
||
const hasVisibleRows = Object.values(visibility).some(Boolean);
|
||
document.querySelectorAll("[data-legend-empty]").forEach((row) => {
|
||
row.hidden = hasVisibleRows;
|
||
});
|
||
const localLegendVisible = Object.entries(visibility).some(
|
||
([key, visible]) => key.startsWith("local-") && visible
|
||
);
|
||
document.querySelectorAll("[data-local-legend-heading]").forEach((row) => {
|
||
row.hidden = !localLegendVisible;
|
||
});
|
||
const legendTitle = "图例 · " + (providerLabels[currentBaseKey] || "当前底图");
|
||
document.querySelectorAll(".legend-title").forEach((title) => {
|
||
title.textContent = legendTitle;
|
||
});
|
||
const printTitle = document.querySelector("#printLegend > strong");
|
||
if (printTitle) printTitle.textContent = legendTitle;
|
||
const boundaryGradient =
|
||
"linear-gradient(90deg, " + boundaryConfig.highColor + " 0 36%, " +
|
||
boundaryConfig.middleColor + " 36% 68%, " +
|
||
boundaryConfig.localColor + " 68% 100%)";
|
||
document.querySelectorAll(".legend-line.boundary").forEach((symbol) => {
|
||
symbol.style.background = boundaryGradient;
|
||
});
|
||
const setLegendBackground = (selector, color) => {
|
||
document.querySelectorAll(selector).forEach((symbol) => {
|
||
symbol.style.background = color;
|
||
symbol.style.opacity = "";
|
||
});
|
||
};
|
||
const setLegendColor = (selector, color) => {
|
||
document.querySelectorAll(selector).forEach((symbol) => {
|
||
symbol.style.color = color;
|
||
});
|
||
};
|
||
document.querySelectorAll(".legend-line.national").forEach((symbol) => {
|
||
if (railwayLineStyle === "railway") {
|
||
symbol.style.border = "1px solid #111";
|
||
symbol.style.background = "repeating-linear-gradient(90deg, #111 0 6px, #fff 6px 12px)";
|
||
} else {
|
||
symbol.style.border = "";
|
||
symbol.style.background = themeColors.national;
|
||
}
|
||
});
|
||
document.querySelectorAll(".legend-line.local-railways").forEach((symbol) => {
|
||
if (railwayLineStyle === "railway") {
|
||
symbol.style.background = "repeating-linear-gradient(90deg, #111 0 6px, #fff 6px 12px)";
|
||
} else {
|
||
symbol.style.background = themeColors.localRailways;
|
||
}
|
||
});
|
||
document.querySelectorAll(".legend-line.metro").forEach((symbol) => {
|
||
symbol.style.background = metroLineStyle === "railway"
|
||
? "repeating-linear-gradient(90deg, #111 0 6px, #fff 6px 12px)"
|
||
: themeColors.metro;
|
||
});
|
||
setLegendBackground(".legend-line.grid", gridConfig.color);
|
||
setLegendBackground(".legend-line.local-roads", themeColors.localRoads);
|
||
setLegendBackground(".legend-line.local-water", themeColors.localWater);
|
||
setLegendBackground(".legend-line.local-province", boundaryConfig.highColor);
|
||
setLegendBackground(".legend-line.local-city", boundaryConfig.middleColor);
|
||
setLegendBackground(
|
||
".legend-line.local-county",
|
||
"repeating-linear-gradient(90deg, " + boundaryConfig.localColor + " 0 6px, transparent 6px 10px)"
|
||
);
|
||
setLegendBackground(".legend-line.local-terrain",
|
||
"repeating-linear-gradient(90deg, " + themeColors.localTerrain + " 0 5px, transparent 5px 9px)");
|
||
[
|
||
[".legend-swatch.water", themeColors.water],
|
||
[".legend-swatch.port", themeColors.port],
|
||
[".legend-swatch.vegetation", themeColors.vegetation],
|
||
[".legend-swatch.local-administration", themeColors.localAdministration],
|
||
[".legend-swatch.local-settlements", themeColors.localSettlements],
|
||
[".legend-swatch.local-vegetation", themeColors.localVegetation],
|
||
[".legend-swatch.local-facilities", themeColors.localFacilities]
|
||
].forEach(([selector, color]) => {
|
||
document.querySelectorAll(selector).forEach((symbol) => {
|
||
symbol.style.background = color;
|
||
symbol.style.opacity = "0.62";
|
||
});
|
||
});
|
||
setLegendColor(".legend-symbol.terrain-peak", themeColors.terrainPeak);
|
||
setLegendColor(".legend-symbol.terrain-valley", themeColors.terrainValley);
|
||
setLegendColor(".legend-symbol.local-heritage", themeColors.localHeritage);
|
||
document.querySelectorAll(".legend-symbol.contour").forEach((symbol) => {
|
||
symbol.style.borderTopColor = contourConfig.color;
|
||
symbol.style.borderBottomColor = contourConfig.color;
|
||
});
|
||
document.querySelectorAll(".legend-swatch.viewshed").forEach((symbol) => {
|
||
symbol.style.background =
|
||
"linear-gradient(90deg, " +
|
||
document.getElementById("visibilityNearColor").value + ", " +
|
||
document.getElementById("visibilityMidColor").value + ", " +
|
||
document.getElementById("visibilityFarColor").value + ")";
|
||
});
|
||
};
|
||
|
||
const updateTerrainFeatures = async () => {
|
||
const sequence = ++terrainFeatureSequence;
|
||
const toggle = document.getElementById("terrainFeatureToggle");
|
||
const peakEnabled = document.getElementById("terrainPeakToggle").checked;
|
||
const valleyEnabled = document.getElementById("terrainValleyToggle").checked;
|
||
const thresholdInput = Number(document.getElementById("terrainProminenceThreshold").value);
|
||
const prominenceThreshold = Number.isFinite(thresholdInput)
|
||
? Math.max(2, Math.min(100, thresholdInput))
|
||
: 30;
|
||
setTerrainFeatureOptionsVisibility(toggle.checked);
|
||
updateLegendVisibility();
|
||
if (!toggle.checked) {
|
||
terrainFeatureLayer.clearLayers();
|
||
if (map.hasLayer(terrainFeatureLayer)) map.removeLayer(terrainFeatureLayer);
|
||
terrainFeatureStatus.textContent = "地形特征点已隐藏。";
|
||
return;
|
||
}
|
||
if (!peakEnabled && !valleyEnabled) {
|
||
terrainFeatureLayer.clearLayers();
|
||
if (map.hasLayer(terrainFeatureLayer)) map.removeLayer(terrainFeatureLayer);
|
||
terrainFeatureStatus.textContent = "山顶与山谷显示均已关闭。";
|
||
return;
|
||
}
|
||
|
||
const displayZoom = map.getZoom();
|
||
if (displayZoom < 10) {
|
||
terrainFeatureLayer.clearLayers();
|
||
if (map.hasLayer(terrainFeatureLayer)) map.removeLayer(terrainFeatureLayer);
|
||
terrainFeatureStatus.textContent = "请放大至 Z10 以上查看地形特征点。";
|
||
return;
|
||
}
|
||
|
||
const bounds = map.getBounds();
|
||
const featureZoom = Math.max(9, Math.min(13, Math.round(displayZoom) - 1));
|
||
const mapSize = map.getSize();
|
||
const cols = Math.max(48, Math.min(96, Math.round(mapSize.x / 12)));
|
||
const rows = Math.max(36, Math.min(96, Math.round(mapSize.y / 12)));
|
||
const north = bounds.getNorth();
|
||
const south = bounds.getSouth();
|
||
const west = bounds.getWest();
|
||
const east = bounds.getEast();
|
||
terrainFeatureStatus.textContent = "正在识别山顶与山谷…";
|
||
|
||
try {
|
||
await ensureDemTilesForBounds(bounds, featureZoom);
|
||
if (
|
||
sequence !== terrainFeatureSequence ||
|
||
Math.abs(map.getZoom() - displayZoom) > 0.001 ||
|
||
!bounds.equals(map.getBounds(), 0.000001)
|
||
) return;
|
||
|
||
const elevations = new Float64Array(cols * rows);
|
||
elevations.fill(NaN);
|
||
const latlngs = new Array(cols * rows);
|
||
let globalMin = Infinity;
|
||
let globalMax = -Infinity;
|
||
for (let row = 0; row < rows; row += 1) {
|
||
const lat = north - (north - south) * row / (rows - 1);
|
||
for (let col = 0; col < cols; col += 1) {
|
||
const lng = west + (east - west) * col / (cols - 1);
|
||
const latlng = L.latLng(lat, lng);
|
||
const elevation = elevationAtLoadedTile(latlng, featureZoom, 1);
|
||
const index = row * cols + col;
|
||
latlngs[index] = latlng;
|
||
if (Number.isFinite(elevation)) {
|
||
elevations[index] = elevation;
|
||
globalMin = Math.min(globalMin, elevation);
|
||
globalMax = Math.max(globalMax, elevation);
|
||
}
|
||
}
|
||
}
|
||
|
||
if (!Number.isFinite(globalMin) || !Number.isFinite(globalMax)) {
|
||
throw new Error("No DEM samples");
|
||
}
|
||
const peakCandidates = [];
|
||
const valleyCandidates = [];
|
||
for (let row = 2; row < rows - 2; row += 1) {
|
||
for (let col = 2; col < cols - 2; col += 1) {
|
||
const index = row * cols + col;
|
||
const center = elevations[index];
|
||
if (!Number.isFinite(center)) continue;
|
||
let neighborMax = -Infinity;
|
||
let neighborMin = Infinity;
|
||
let aroundMax = -Infinity;
|
||
let aroundMin = Infinity;
|
||
for (let offsetY = -2; offsetY <= 2; offsetY += 1) {
|
||
for (let offsetX = -2; offsetX <= 2; offsetX += 1) {
|
||
const value = elevations[(row + offsetY) * cols + col + offsetX];
|
||
if (!Number.isFinite(value)) continue;
|
||
aroundMax = Math.max(aroundMax, value);
|
||
aroundMin = Math.min(aroundMin, value);
|
||
if (Math.abs(offsetX) <= 1 && Math.abs(offsetY) <= 1 && (offsetX || offsetY)) {
|
||
neighborMax = Math.max(neighborMax, value);
|
||
neighborMin = Math.min(neighborMin, value);
|
||
}
|
||
}
|
||
}
|
||
if (!Number.isFinite(neighborMin) || !Number.isFinite(neighborMax)) continue;
|
||
if (peakEnabled && center >= neighborMax - 0.4 && center - aroundMin >= prominenceThreshold) {
|
||
peakCandidates.push({
|
||
latlng: latlngs[index],
|
||
elevation: center,
|
||
prominence: center - aroundMin
|
||
});
|
||
}
|
||
if (valleyEnabled && center <= neighborMin + 0.4 && aroundMax - center >= prominenceThreshold) {
|
||
valleyCandidates.push({
|
||
latlng: latlngs[index],
|
||
elevation: center,
|
||
prominence: aroundMax - center
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
const selectSpaced = (candidates) => {
|
||
const selected = [];
|
||
candidates
|
||
.sort((a, b) => b.prominence - a.prominence)
|
||
.forEach((candidate) => {
|
||
if (selected.length >= 18) return;
|
||
const point = map.latLngToContainerPoint(candidate.latlng);
|
||
if (selected.some((entry) => {
|
||
const other = map.latLngToContainerPoint(entry.latlng);
|
||
return Math.hypot(point.x - other.x, point.y - other.y) < 54;
|
||
})) return;
|
||
selected.push(candidate);
|
||
});
|
||
return selected;
|
||
};
|
||
|
||
const peaks = peakEnabled ? selectSpaced(peakCandidates) : [];
|
||
const valleys = valleyEnabled ? selectSpaced(valleyCandidates) : [];
|
||
terrainFeatureLayer.clearLayers();
|
||
const addFeatureMarker = (candidate, type) => {
|
||
const isPeak = type === "peak";
|
||
const symbol = isPeak ? "▲" : "▼";
|
||
const label = isPeak ? "近似山顶" : "近似山谷";
|
||
const icon = L.divIcon({
|
||
className: "terrain-feature-marker " + type,
|
||
html: "<span>" + symbol + "</span>",
|
||
iconSize: [18, 18],
|
||
iconAnchor: [9, 9]
|
||
});
|
||
terrainFeatureLayer.addLayer(
|
||
L.marker(candidate.latlng, { icon, riseOnHover: true }).bindTooltip(
|
||
label + " " + candidate.elevation.toFixed(0) + " m",
|
||
{ direction: "top", offset: [0, -8], opacity: 0.92 }
|
||
).bindPopup(() =>
|
||
"<strong>" + label + "</strong>" +
|
||
"<br>高程:" + candidate.elevation.toFixed(1) + " m" +
|
||
"<br>近似起伏:" + candidate.prominence.toFixed(1) + " m" +
|
||
"<br>位置:" + formatLatLng(candidate.latlng)
|
||
)
|
||
);
|
||
};
|
||
peaks.forEach((candidate) => addFeatureMarker(candidate, "peak"));
|
||
valleys.forEach((candidate) => addFeatureMarker(candidate, "valley"));
|
||
if (!map.hasLayer(terrainFeatureLayer)) map.addLayer(terrainFeatureLayer);
|
||
terrainFeatureStatus.textContent =
|
||
peaks.length || valleys.length
|
||
? "当前视窗:山顶 " + (peakEnabled ? peaks.length : "关闭") +
|
||
" · 山谷 " + (valleyEnabled ? valleys.length : "关闭") +
|
||
"(阈值 " + prominenceThreshold + " m)"
|
||
: "当前视窗未识别到超过 " + prominenceThreshold + " m 的地形特征点。";
|
||
} catch (error) {
|
||
if (sequence !== terrainFeatureSequence) return;
|
||
terrainFeatureLayer.clearLayers();
|
||
terrainFeatureStatus.textContent = "地形特征点识别失败,请放大地图后重试。";
|
||
}
|
||
};
|
||
|
||
const scheduleTerrainFeatureUpdate = () => {
|
||
window.clearTimeout(terrainFeatureTimer);
|
||
terrainFeatureTimer = window.setTimeout(updateTerrainFeatures, 320);
|
||
};
|
||
|
||
const updateDrawingStatus = (message) => {
|
||
drawingStatus.textContent = message;
|
||
};
|
||
|
||
const createDrawingVisibilityButton = (item) => {
|
||
const button = document.createElement("button");
|
||
button.type = "button";
|
||
button.className = "drawing-visibility";
|
||
button.textContent = item.visible === false ? "显示" : "隐藏";
|
||
button.setAttribute("aria-pressed", item.visible === false ? "false" : "true");
|
||
button.title = item.visible === false ? "在地图上显示" : "在地图上隐藏";
|
||
const toggle = (event) => {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
setDrawingVisibility(item, item.visible === false);
|
||
renderDrawingList();
|
||
showToast((item.visible ? "已显示:" : "已隐藏:") + item.name);
|
||
};
|
||
button.addEventListener("click", toggle);
|
||
return button;
|
||
};
|
||
|
||
const createDrawingAppearanceControls = (item) => {
|
||
const controls = document.createElement("div");
|
||
controls.className = "drawing-style-controls";
|
||
|
||
const colorLabel = document.createElement("label");
|
||
colorLabel.className = "drawing-color-control";
|
||
const colorText = document.createElement("span");
|
||
colorText.textContent = "颜色";
|
||
const colorInput = document.createElement("input");
|
||
colorInput.type = "color";
|
||
colorInput.value = item.color || defaultDrawingColor(item.type, item);
|
||
colorInput.setAttribute("aria-label", "绘制颜色");
|
||
colorInput.addEventListener("input", () => {
|
||
item.color = colorInput.value;
|
||
item.customColor = true;
|
||
if (item.type === "observation") {
|
||
item.colorBands = { near: item.color, mid: item.color, far: item.color };
|
||
if (item.observation) {
|
||
item.observation.colorBands = { ...item.colorBands };
|
||
}
|
||
}
|
||
applyDrawingStyle(item);
|
||
scheduleDrawingSave();
|
||
});
|
||
colorInput.addEventListener("change", () => scheduleDrawingSave());
|
||
colorLabel.append(colorText, colorInput);
|
||
|
||
const opacityLabel = document.createElement("label");
|
||
opacityLabel.className = "drawing-opacity-control";
|
||
const opacityText = document.createElement("span");
|
||
opacityText.textContent = "不透明度";
|
||
const opacityOutput = document.createElement("output");
|
||
opacityOutput.textContent = Math.round((item.opacity ?? 1) * 100) + "%";
|
||
const opacityInput = document.createElement("input");
|
||
opacityInput.type = "range";
|
||
opacityInput.min = "0";
|
||
opacityInput.max = "100";
|
||
opacityInput.step = "1";
|
||
opacityInput.value = String(Math.round((item.opacity ?? 1) * 100));
|
||
opacityInput.setAttribute("aria-label", "绘制不透明度");
|
||
opacityInput.addEventListener("input", () => {
|
||
item.opacity = Number(opacityInput.value) / 100;
|
||
opacityOutput.textContent = opacityInput.value + "%";
|
||
applyDrawingStyle(item);
|
||
scheduleDrawingSave();
|
||
});
|
||
opacityInput.addEventListener("change", () => scheduleDrawingSave());
|
||
opacityText.appendChild(opacityOutput);
|
||
opacityLabel.append(opacityText, opacityInput);
|
||
|
||
controls.append(colorLabel, opacityLabel);
|
||
return controls;
|
||
};
|
||
|
||
const createDrawingStyleRow = (item) => {
|
||
const row = document.createElement("div");
|
||
row.className = "drawing-style-row";
|
||
row.append(createDrawingVisibilityButton(item), createDrawingAppearanceControls(item));
|
||
return row;
|
||
};
|
||
|
||
const renderDrawingList = () => {
|
||
drawingList.replaceChildren();
|
||
if (!drawingItems.length) {
|
||
const empty = document.createElement("p");
|
||
empty.className = "drawing-empty";
|
||
empty.textContent = "暂无已保存的绘制内容";
|
||
drawingList.appendChild(empty);
|
||
updateLegendVisibility();
|
||
return;
|
||
}
|
||
|
||
const appendNodeList = (container, profile) => {
|
||
if (!profile.nodes?.length) return;
|
||
const nodeHeading = document.createElement("div");
|
||
nodeHeading.className = "node-list-heading";
|
||
nodeHeading.innerHTML = "<span>节点位置</span><span>高程</span>";
|
||
const nodeList = document.createElement("div");
|
||
nodeList.className = "node-list";
|
||
profile.nodes.forEach((node, index) => {
|
||
const nodeRow = document.createElement("div");
|
||
nodeRow.className = "node-row";
|
||
const nodeCopy = document.createElement("div");
|
||
const nodeName = document.createElement("strong");
|
||
nodeName.textContent = "节点 " + (index + 1);
|
||
const location = document.createElement("span");
|
||
location.textContent = formatLatLng(node) + " · 里程 " + formatDistance(node.distance);
|
||
nodeCopy.append(nodeName, location);
|
||
const elevation = document.createElement("span");
|
||
elevation.className = "node-elevation";
|
||
elevation.textContent = Number.isFinite(node.elevation)
|
||
? node.elevation.toFixed(1) + " m"
|
||
: "—";
|
||
nodeRow.append(nodeCopy, elevation);
|
||
nodeList.appendChild(nodeRow);
|
||
});
|
||
container.append(nodeHeading, nodeList);
|
||
};
|
||
|
||
drawingItems.forEach((item) => {
|
||
const row = document.createElement(item.type === "path" ? "details" : "div");
|
||
row.className = "drawing-card" + (item.type === "path" ? " drawing-fold" : "");
|
||
row.classList.toggle("is-hidden", item.visible === false);
|
||
row.dataset.drawingId = item.id;
|
||
row.dataset.drawingType = item.type;
|
||
if (item.type === "path") {
|
||
row.open = Boolean(item.expanded);
|
||
row.addEventListener("toggle", () => {
|
||
item.expanded = row.open;
|
||
if (row.open && item.profile?.status === "ready") {
|
||
window.requestAnimationFrame(() => drawPathProfile(row.querySelector(".profile-canvas"), item.profile));
|
||
}
|
||
});
|
||
}
|
||
|
||
const nameInput = document.createElement("input");
|
||
nameInput.className = "drawing-name";
|
||
nameInput.value = item.name;
|
||
nameInput.setAttribute("aria-label", "名称");
|
||
nameInput.addEventListener("change", () => {
|
||
item.name = nameInput.value.trim() || item.name;
|
||
nameInput.value = item.name;
|
||
const title = row.querySelector(".drawing-title");
|
||
if (title) title.textContent = item.name;
|
||
scheduleDrawingSave();
|
||
});
|
||
|
||
const deleteButton = document.createElement("button");
|
||
deleteButton.className = "drawing-delete";
|
||
deleteButton.type = "button";
|
||
deleteButton.textContent = "删除";
|
||
deleteButton.addEventListener("click", () => {
|
||
drawingGroup.removeLayer(item.layer);
|
||
const index = drawingItems.findIndex((candidate) => candidate.id === item.id);
|
||
if (index >= 0) drawingItems.splice(index, 1);
|
||
renderDrawingList();
|
||
scheduleDrawingSave();
|
||
showToast("已删除:" + item.name);
|
||
});
|
||
|
||
if (item.type === "path") {
|
||
const summary = document.createElement("summary");
|
||
summary.className = "drawing-summary";
|
||
const summaryCopy = document.createElement("div");
|
||
const title = document.createElement("strong");
|
||
title.className = "drawing-title";
|
||
title.textContent = item.name;
|
||
const meta = document.createElement("span");
|
||
meta.className = "drawing-meta";
|
||
meta.textContent = item.detail;
|
||
summaryCopy.append(title, meta);
|
||
summary.append(summaryCopy, createDrawingVisibilityButton(item));
|
||
row.appendChild(summary);
|
||
|
||
const body = document.createElement("div");
|
||
body.className = "drawing-body";
|
||
const toolbar = document.createElement("div");
|
||
toolbar.className = "drawing-toolbar";
|
||
toolbar.append(nameInput, deleteButton);
|
||
body.appendChild(toolbar);
|
||
body.appendChild(createDrawingAppearanceControls(item));
|
||
|
||
const profile = document.createElement("div");
|
||
profile.className = "path-profile";
|
||
if (!item.profile || item.profile.status === "loading") {
|
||
const loading = document.createElement("p");
|
||
loading.className = "profile-message";
|
||
loading.textContent = "正在读取每个节点的高程与位置…";
|
||
profile.appendChild(loading);
|
||
} else if (item.profile.status === "error") {
|
||
const error = document.createElement("p");
|
||
error.className = "profile-message is-error";
|
||
error.textContent = "高程数据读取失败,请稍后重新绘制。";
|
||
profile.appendChild(error);
|
||
appendNodeList(profile, item.profile);
|
||
} else {
|
||
const profileHeading = document.createElement("div");
|
||
profileHeading.className = "profile-heading";
|
||
const heading = document.createElement("strong");
|
||
heading.textContent = "高程剖面";
|
||
const profileMeta = document.createElement("span");
|
||
profileMeta.textContent = item.profile.nodes.length + " 个节点 · " + formatDistance(item.profile.totalLength);
|
||
profileHeading.append(heading, profileMeta);
|
||
|
||
const canvas = document.createElement("canvas");
|
||
canvas.className = "profile-canvas";
|
||
canvas.setAttribute("aria-label", item.name + "的高程剖面;节点位置见下方列表");
|
||
|
||
profile.append(profileHeading, canvas);
|
||
appendNodeList(profile, item.profile);
|
||
window.requestAnimationFrame(() => drawPathProfile(canvas, item.profile));
|
||
}
|
||
body.appendChild(profile);
|
||
row.appendChild(body);
|
||
} else {
|
||
const main = document.createElement("div");
|
||
main.className = "drawing-main";
|
||
const content = document.createElement("div");
|
||
content.className = "drawing-copy";
|
||
const meta = document.createElement("div");
|
||
meta.className = "drawing-meta";
|
||
meta.textContent = item.detail;
|
||
content.append(nameInput, meta);
|
||
main.append(content, deleteButton);
|
||
row.appendChild(main);
|
||
row.appendChild(createDrawingStyleRow(item));
|
||
}
|
||
|
||
drawingList.appendChild(row);
|
||
});
|
||
updateLegendVisibility();
|
||
};
|
||
|
||
const DRAWING_STORAGE_KEY = "mapStudio.drawings.v1";
|
||
let isRestoringDrawings = false;
|
||
let isImportingProject = false;
|
||
let drawingSaveTimer = null;
|
||
|
||
const pointRecord = (point) => ({ lat: Number(point.lat), lng: Number(point.lng) });
|
||
const pointsRecord = (points) => (points || []).map(pointRecord);
|
||
const pointsFromRecord = (points) => (points || [])
|
||
.filter((point) => Number.isFinite(Number(point.lat)) && Number.isFinite(Number(point.lng)))
|
||
.map((point) => L.latLng(Number(point.lat), Number(point.lng)));
|
||
|
||
const drawingItemToRecord = (item) => {
|
||
const record = {
|
||
type: item.type,
|
||
name: item.name,
|
||
detail: item.detail,
|
||
style: {
|
||
visible: item.visible !== false,
|
||
color: item.color,
|
||
opacity: Number.isFinite(Number(item.opacity)) ? Number(item.opacity) : 1,
|
||
customColor: Boolean(item.customColor)
|
||
}
|
||
};
|
||
if (item.type === "path") {
|
||
record.points = pointsRecord(item.points);
|
||
if (item.profile) record.profile = item.profile;
|
||
} else if (item.type === "range") {
|
||
record.points = pointsRecord(item.points);
|
||
} else if (item.type === "viewshed") {
|
||
record.viewshed = item.viewshed;
|
||
} else if (item.type === "observation") {
|
||
record.observation = item.observation;
|
||
}
|
||
return record;
|
||
};
|
||
|
||
const captureDrawingsState = () => ({
|
||
version: 1,
|
||
savedAt: new Date().toISOString(),
|
||
counts: { ...drawingCounts },
|
||
items: drawingItems.map(drawingItemToRecord)
|
||
});
|
||
|
||
const saveDrawingsNow = () => {
|
||
if (isRestoringDrawings || isImportingProject) return;
|
||
window.clearTimeout(drawingSaveTimer);
|
||
drawingSaveTimer = null;
|
||
const payload = captureDrawingsState();
|
||
try {
|
||
window.localStorage.setItem(DRAWING_STORAGE_KEY, JSON.stringify(payload));
|
||
} catch (error) {
|
||
updateDrawingStatus("浏览器无法保存绘制内容,请检查本地存储权限。");
|
||
}
|
||
};
|
||
|
||
const scheduleDrawingSave = () => {
|
||
if (isRestoringDrawings || isImportingProject) return;
|
||
window.clearTimeout(drawingSaveTimer);
|
||
drawingSaveTimer = window.setTimeout(saveDrawingsNow, 100);
|
||
};
|
||
|
||
const restoreDrawingsFromStorage = () => {
|
||
drawingGeneration += 1;
|
||
drawingGroup.clearLayers();
|
||
drawingItems.splice(0, drawingItems.length);
|
||
Object.keys(drawingCounts).forEach((type) => {
|
||
drawingCounts[type] = 0;
|
||
});
|
||
clearDrawingState();
|
||
|
||
let payload = null;
|
||
try {
|
||
payload = JSON.parse(window.localStorage.getItem(DRAWING_STORAGE_KEY) || "null");
|
||
} catch (error) {
|
||
return;
|
||
}
|
||
if (!payload || payload.version !== 1 || !Array.isArray(payload.items)) return;
|
||
|
||
isRestoringDrawings = true;
|
||
const deferredObservations = [];
|
||
payload.items.forEach((record) => {
|
||
if (!record || !record.type) return;
|
||
const savedStyle = record.style || {};
|
||
const shared = {
|
||
name: record.name,
|
||
detail: record.detail,
|
||
visible: savedStyle.visible !== false,
|
||
color: savedStyle.color,
|
||
opacity: Number.isFinite(Number(savedStyle.opacity)) ? Number(savedStyle.opacity) : 1,
|
||
customColor: Boolean(savedStyle.customColor)
|
||
};
|
||
|
||
if (record.type === "path") {
|
||
const points = pointsFromRecord(record.points);
|
||
if (points.length < 2) return;
|
||
const line = L.polyline(points, { color: "#245da8", weight: 3.2, opacity: 0.92 });
|
||
const layer = L.layerGroup([line]);
|
||
const profile = record.profile && record.profile.status === "ready" ? record.profile : null;
|
||
if (profile?.nodes) {
|
||
profile.nodes.forEach((node, index) => {
|
||
layer.addLayer(
|
||
L.circleMarker([node.lat, node.lng], {
|
||
radius: 4.5,
|
||
color: "#ffffff",
|
||
weight: 1.7,
|
||
fillColor: "#245da8",
|
||
fillOpacity: 1
|
||
}).bindPopup(() =>
|
||
"<strong>路径节点 " + (index + 1) + "</strong>" +
|
||
"<br>位置:" + formatLatLng(node) +
|
||
"<br>高程:" + Number(node.elevation).toFixed(1) + " m" +
|
||
"<br>里程:" + formatDistance(node.distance)
|
||
)
|
||
);
|
||
});
|
||
}
|
||
const item = addDrawingItem("path", layer, record.detail || "", { ...shared, points, profile, expanded: false });
|
||
if (!profile) {
|
||
const directDistance = haversineDistance(points[0], points[points.length - 1]);
|
||
void analyzePathProfile(item, directDistance);
|
||
}
|
||
return;
|
||
}
|
||
|
||
if (record.type === "range") {
|
||
const points = pointsFromRecord(record.points);
|
||
if (points.length < 3) return;
|
||
const area = sphericalPolygonArea(points);
|
||
const polygon = L.polygon(points, {
|
||
color: "#205c46",
|
||
weight: 2.6,
|
||
fillColor: "#205c46",
|
||
fillOpacity: 0.16,
|
||
interactive: false
|
||
});
|
||
polygon.bindPopup("<strong>绘制范围</strong><br>面积:" + formatArea(area));
|
||
addDrawingItem("range", polygon, record.detail || "面积 " + formatArea(area), { ...shared, points });
|
||
return;
|
||
}
|
||
|
||
if (record.type === "viewshed" && record.viewshed) {
|
||
const start = L.latLng(record.viewshed.start);
|
||
const end = L.latLng(record.viewshed.end);
|
||
const analysis = record.viewshed.analysis;
|
||
if (!analysis || !analysis.elevations?.length) return;
|
||
const group = createPairViewshedLayer(start, end, Number(record.viewshed.sightHeight), analysis);
|
||
addDrawingItem("viewshed", group, record.detail || "", { ...shared, viewshed: record.viewshed });
|
||
return;
|
||
}
|
||
|
||
if (record.type === "observation" && record.observation) {
|
||
const observation = record.observation;
|
||
const center = L.latLng(observation.center);
|
||
const placeholder = L.layerGroup([
|
||
L.circle(center, {
|
||
radius: Number(observation.outerRadius),
|
||
color: "#315a47",
|
||
weight: 1.2,
|
||
dashArray: "6 5",
|
||
fill: false,
|
||
interactive: false
|
||
}),
|
||
L.circleMarker(center, {
|
||
radius: 7,
|
||
color: "#ffffff",
|
||
weight: 2.4,
|
||
fillColor: "#174c38",
|
||
fillOpacity: 1
|
||
})
|
||
]);
|
||
const item = addDrawingItem(
|
||
"observation",
|
||
placeholder,
|
||
(record.detail || "") + " · 正在恢复显示",
|
||
{ ...shared, observation: { ...observation } }
|
||
);
|
||
deferredObservations.push(item);
|
||
}
|
||
});
|
||
|
||
["path", "range", "viewshed", "observation"].forEach((type) => {
|
||
const saved = Number(payload.counts?.[type]);
|
||
if (Number.isFinite(saved)) drawingCounts[type] = Math.max(drawingCounts[type], saved);
|
||
});
|
||
renderDrawingList();
|
||
isRestoringDrawings = false;
|
||
if (drawingItems.length) {
|
||
updateDrawingStatus("已从浏览器恢复 " + drawingItems.length + " 项绘制内容。");
|
||
}
|
||
deferredObservations.forEach((item) => {
|
||
void analyzeVisibilityArea(L.latLng(item.observation.center), {
|
||
existingItem: item,
|
||
config: item.observation,
|
||
silent: true
|
||
});
|
||
});
|
||
};
|
||
|
||
const addDrawingItem = (type, layer, detail, data) => {
|
||
drawingCounts[type] += 1;
|
||
const labels = { path: "路径", range: "范围", viewshed: "两点通视", observation: "通视观察" };
|
||
const item = {
|
||
id: Date.now() + "-" + Math.random().toString(16).slice(2),
|
||
type,
|
||
name: labels[type] + drawingCounts[type],
|
||
detail,
|
||
layer,
|
||
...(data || {}),
|
||
visible: data?.visible !== false,
|
||
color: data?.color || defaultDrawingColor(type, data),
|
||
opacity: Number.isFinite(Number(data?.opacity)) ? Math.max(0, Math.min(1, Number(data.opacity))) : 1,
|
||
customColor: Boolean(data?.customColor)
|
||
};
|
||
drawingItems.push(item);
|
||
applyDrawingStyle(item);
|
||
if (item.visible) drawingGroup.addLayer(layer);
|
||
renderDrawingList();
|
||
scheduleDrawingSave();
|
||
return item;
|
||
};
|
||
|
||
const clearDrawingState = () => {
|
||
visibilityTask += 1;
|
||
if (temporaryShape) drawingGroup.removeLayer(temporaryShape);
|
||
drawingMode = null;
|
||
drawingPoints = [];
|
||
temporaryShape = null;
|
||
viewshedStart = null;
|
||
document.body.classList.remove("drawing-mode");
|
||
map.doubleClickZoom.enable();
|
||
document.querySelectorAll(".tool-button").forEach((button) => button.classList.remove("active"));
|
||
document.getElementById("finishDrawingButton").hidden = true;
|
||
};
|
||
|
||
const clearAllDrawings = () => {
|
||
drawingGeneration += 1;
|
||
drawingGroup.clearLayers();
|
||
drawingItems.splice(0, drawingItems.length);
|
||
Object.keys(drawingCounts).forEach((type) => {
|
||
drawingCounts[type] = 0;
|
||
});
|
||
clearDrawingState();
|
||
renderDrawingList();
|
||
window.clearTimeout(drawingSaveTimer);
|
||
try {
|
||
window.localStorage.removeItem(DRAWING_STORAGE_KEY);
|
||
} catch (error) {
|
||
// Ignore unavailable local storage; the visible drawings are still cleared.
|
||
}
|
||
updateDrawingStatus("选择一个工具开始绘制。");
|
||
};
|
||
|
||
const renderTemporaryShape = () => {
|
||
if (temporaryShape) drawingGroup.removeLayer(temporaryShape);
|
||
if (drawingPoints.length < 2) return;
|
||
|
||
const options = {
|
||
color: drawingMode === "range" ? "#205c46" : "#245da8",
|
||
weight: 2.4,
|
||
dashArray: "7 6",
|
||
fill: drawingMode === "range",
|
||
fillColor: "#205c46",
|
||
fillOpacity: 0.12,
|
||
interactive: false
|
||
};
|
||
|
||
temporaryShape = drawingMode === "range"
|
||
? L.polygon(drawingPoints, options)
|
||
: L.polyline(drawingPoints, options);
|
||
drawingGroup.addLayer(temporaryShape);
|
||
};
|
||
|
||
const finishDrawing = () => {
|
||
if (drawingMode === "path" && drawingPoints.length >= 2) {
|
||
const line = L.polyline(drawingPoints, { color: "#245da8", weight: 3.2, opacity: 0.92 });
|
||
const distance = drawingPoints.reduce((sum, point, index) => {
|
||
return index ? sum + haversineDistance(drawingPoints[index - 1], point) : 0;
|
||
}, 0);
|
||
const directDistance = haversineDistance(drawingPoints[0], drawingPoints[drawingPoints.length - 1]);
|
||
line.bindPopup("<strong>绘制路径</strong><br>总长:" + formatDistance(distance) + "<br>首尾直线:" + formatDistance(directDistance));
|
||
const pathLayer = L.layerGroup([line]);
|
||
const item = addDrawingItem(
|
||
"path",
|
||
pathLayer,
|
||
"总长 " + formatDistance(distance) + " · 直线 " + formatDistance(directDistance),
|
||
{ points: drawingPoints.slice(), expanded: false }
|
||
);
|
||
updateDrawingStatus("路径已保存,总长 " + formatDistance(distance) + "。");
|
||
void analyzePathProfile(item, directDistance);
|
||
} else if (drawingMode === "range" && drawingPoints.length >= 3) {
|
||
const polygon = L.polygon(drawingPoints, {
|
||
color: "#205c46",
|
||
weight: 2.6,
|
||
fillColor: "#205c46",
|
||
fillOpacity: 0.16,
|
||
interactive: false
|
||
});
|
||
const area = sphericalPolygonArea(drawingPoints);
|
||
polygon.bindPopup("<strong>绘制范围</strong><br>面积:" + formatArea(area));
|
||
addDrawingItem("range", polygon, "面积 " + formatArea(area), { points: drawingPoints.slice() });
|
||
updateDrawingStatus("范围已保存,面积 " + formatArea(area) + "。");
|
||
} else {
|
||
showToast("绘制点不足:路径至少 2 点,范围至少 3 点。", "error");
|
||
return;
|
||
}
|
||
|
||
if (temporaryShape) drawingGroup.removeLayer(temporaryShape);
|
||
clearDrawingState();
|
||
};
|
||
|
||
const createPairViewshedLayer = (start, end, sightHeight, analysis) => {
|
||
const elevations = analysis.elevations;
|
||
const itemGroup = L.layerGroup();
|
||
const line = L.polyline([start, end], {
|
||
color: analysis.visible ? "#1f9d62" : "#c64a3b",
|
||
weight: 3.2,
|
||
dashArray: analysis.visible ? null : "8 7",
|
||
opacity: 0.95
|
||
});
|
||
line.bindPopup(
|
||
"<strong>通视分析</strong><br>结果:" + (analysis.visible ? "可见" : "不可见") +
|
||
"<br>距离:" + formatDistance(analysis.distance) +
|
||
"<br>起点高程:" + elevations[0].toFixed(1) + " m" +
|
||
"<br>终点高程:" + elevations[elevations.length - 1].toFixed(1) + " m" +
|
||
"<br>视线高度:" + sightHeight.toFixed(1) + " m"
|
||
);
|
||
itemGroup.addLayer(line);
|
||
itemGroup.addLayer(
|
||
L.circleMarker(start, { radius: 6, color: "#fff", weight: 2, fillColor: "#245da8", fillOpacity: 1 })
|
||
.bindPopup("观察点<br>高程:" + elevations[0].toFixed(1) + " m")
|
||
);
|
||
itemGroup.addLayer(
|
||
L.circleMarker(end, { radius: 6, color: "#fff", weight: 2, fillColor: "#7b4fc4", fillOpacity: 1 })
|
||
.bindPopup("目标点<br>高程:" + elevations[elevations.length - 1].toFixed(1) + " m")
|
||
);
|
||
if (!analysis.visible && analysis.blockedIndex > 0) {
|
||
const ratio = analysis.blockedIndex / analysis.sampleCount;
|
||
const blockedPoint = L.latLng(
|
||
start.lat + (end.lat - start.lat) * ratio,
|
||
start.lng + (end.lng - start.lng) * ratio
|
||
);
|
||
itemGroup.addLayer(
|
||
L.circleMarker(blockedPoint, {
|
||
radius: 7,
|
||
color: "#fff",
|
||
weight: 2,
|
||
fillColor: "#c64a3b",
|
||
fillOpacity: 1
|
||
}).bindPopup("遮挡点<br>高程:" + elevations[analysis.blockedIndex].toFixed(1) + " m")
|
||
);
|
||
}
|
||
return itemGroup;
|
||
};
|
||
|
||
const analyzeViewshed = async (start, end) => {
|
||
const generation = drawingGeneration;
|
||
updateDrawingStatus("正在读取高程并计算通视…");
|
||
const sampleCount = 64;
|
||
const samples = Array.from({ length: sampleCount + 1 }, (_, index) => {
|
||
const ratio = index / sampleCount;
|
||
return L.latLng(
|
||
start.lat + (end.lat - start.lat) * ratio,
|
||
start.lng + (end.lng - start.lng) * ratio
|
||
);
|
||
});
|
||
|
||
const elevations = await Promise.all(samples.map(getElevationAt));
|
||
if (generation !== drawingGeneration) return;
|
||
if (elevations.some((value) => value === null || !Number.isFinite(value))) {
|
||
updateDrawingStatus("高程数据加载失败,请稍后重试。");
|
||
showToast("高程数据加载失败,无法完成通视分析。", "error");
|
||
return;
|
||
}
|
||
|
||
const sightHeightInput = Number(document.getElementById("viewshedHeight").value);
|
||
const sightHeight = Number.isFinite(sightHeightInput) && sightHeightInput >= 0 ? sightHeightInput : 1;
|
||
const observerElevation = elevations[0] + sightHeight;
|
||
const targetElevation = elevations[elevations.length - 1] + sightHeight;
|
||
let blockedIndex = -1;
|
||
|
||
for (let index = 1; index < elevations.length - 1; index += 1) {
|
||
const ratio = index / sampleCount;
|
||
const sightline = observerElevation + (targetElevation - observerElevation) * ratio;
|
||
if (elevations[index] > sightline + 0.5) {
|
||
blockedIndex = index;
|
||
break;
|
||
}
|
||
}
|
||
|
||
const distance = haversineDistance(start, end);
|
||
const visible = blockedIndex < 0;
|
||
const analysis = { elevations, blockedIndex, sampleCount, distance, visible };
|
||
const itemGroup = createPairViewshedLayer(start, end, sightHeight, analysis);
|
||
|
||
addDrawingItem(
|
||
"viewshed",
|
||
itemGroup,
|
||
(visible ? "可见" : "不可见") + " · " + formatDistance(distance) + " · 视线高 " + sightHeight.toFixed(1) + " m",
|
||
{
|
||
viewshed: {
|
||
start: pointRecord(start),
|
||
end: pointRecord(end),
|
||
sightHeight,
|
||
analysis
|
||
}
|
||
}
|
||
);
|
||
|
||
updateDrawingStatus(
|
||
"通视结果:" + (visible ? "可见" : "不可见") +
|
||
";距离 " + formatDistance(distance) + ";视线高度 " + sightHeight.toFixed(1) + " m" +
|
||
(visible ? "。" : ";红色点为首个明显遮挡位置。")
|
||
);
|
||
showToast("通视分析完成:" + (visible ? "两点可见。" : "两点之间存在地形遮挡。"), visible ? "success" : "error");
|
||
clearDrawingState();
|
||
};
|
||
|
||
const startDrawing = (mode) => {
|
||
clearDrawingState();
|
||
map.closePopup();
|
||
drawingMode = mode;
|
||
document.body.classList.add("drawing-mode");
|
||
map.doubleClickZoom.disable();
|
||
document.getElementById("finishDrawingButton").hidden = mode === "viewshed" || mode === "observation";
|
||
const toolButtons = {
|
||
path: "pathDrawButton",
|
||
range: "rangeDrawButton",
|
||
viewshed: "viewshedButton",
|
||
observation: "visibilityObservationButton"
|
||
};
|
||
document.getElementById(toolButtons[mode]).classList.add("active");
|
||
|
||
if (mode === "viewshed") {
|
||
updateDrawingStatus("点击地图选择观察点,再点击目标点。");
|
||
} else if (mode === "observation") {
|
||
document.getElementById("visibilityOptions").open = true;
|
||
updateDrawingStatus("设置内、外半径后,在地图上点击一个观察点。");
|
||
} else {
|
||
updateDrawingStatus(mode === "path" ? "点击地图添加路径点,完成后点击“完成绘制”。" : "点击地图添加范围顶点,完成后点击“完成绘制”。");
|
||
}
|
||
};
|
||
|
||
map.on("click", (event) => {
|
||
if (!drawingMode) return;
|
||
|
||
if (drawingMode === "path" || drawingMode === "range") {
|
||
drawingPoints.push(event.latlng);
|
||
renderTemporaryShape();
|
||
updateDrawingStatus("已添加 " + drawingPoints.length + " 个点。");
|
||
return;
|
||
}
|
||
|
||
if (drawingMode === "viewshed") {
|
||
if (!viewshedStart) {
|
||
viewshedStart = event.latlng;
|
||
temporaryShape = L.circleMarker(viewshedStart, {
|
||
radius: 6,
|
||
color: "#fff",
|
||
weight: 2,
|
||
fillColor: "#245da8",
|
||
fillOpacity: 1
|
||
});
|
||
drawingGroup.addLayer(temporaryShape);
|
||
updateDrawingStatus("已选择观察点,点击目标点进行通视分析。");
|
||
} else {
|
||
analyzeViewshed(viewshedStart, event.latlng);
|
||
}
|
||
return;
|
||
}
|
||
|
||
if (drawingMode === "observation") {
|
||
if (temporaryShape) drawingGroup.removeLayer(temporaryShape);
|
||
viewshedStart = event.latlng;
|
||
temporaryShape = L.circleMarker(viewshedStart, {
|
||
radius: 6,
|
||
color: "#ffffff",
|
||
weight: 2,
|
||
fillColor: "#174c38",
|
||
fillOpacity: 1
|
||
});
|
||
drawingGroup.addLayer(temporaryShape);
|
||
void analyzeVisibilityArea(viewshedStart);
|
||
}
|
||
});
|
||
const setStatus = (message, mode) => {
|
||
statusText.textContent = message;
|
||
statusPill.classList.remove("is-busy", "is-error");
|
||
if (mode === "busy") statusPill.classList.add("is-busy");
|
||
if (mode === "error") statusPill.classList.add("is-error");
|
||
};
|
||
|
||
const showToast = (message, type) => {
|
||
window.clearTimeout(toastTimer);
|
||
toast.textContent = message;
|
||
toast.className = "toast show" + (type === "error" ? " error" : "");
|
||
toastTimer = window.setTimeout(() => {
|
||
toast.className = "toast";
|
||
}, 4200);
|
||
};
|
||
|
||
const formatCoordinateReadout = (latlng) => {
|
||
if (!coordinateSystems) {
|
||
if (coordinateReadoutFormat === "dms") {
|
||
return formatDmsValue(latlng.lat, "lat", 2) + ", " +
|
||
formatDmsValue(latlng.lng, "lng", 2);
|
||
}
|
||
return Math.abs(latlng.lat).toFixed(6) + "° " + (latlng.lat >= 0 ? "N" : "S") + ", " +
|
||
Math.abs(latlng.lng).toFixed(6) + "° " + (latlng.lng >= 0 ? "E" : "W");
|
||
}
|
||
const system = coordinateSystems.getSystem(selectedCoordinateSystem);
|
||
const coordinates = coordinateSystems.toSystemCoordinates(
|
||
latlng.lat,
|
||
latlng.lng,
|
||
system.id
|
||
);
|
||
if (coordinates.kind === "projected") {
|
||
return coordinateSystems.format(latlng.lat, latlng.lng, system.id, {
|
||
includeSystem: true,
|
||
precision: 6
|
||
});
|
||
}
|
||
if (coordinateReadoutFormat === "dms") {
|
||
return system.label + " " +
|
||
formatDmsValue(coordinates.lat, "lat", 2) + ", " +
|
||
formatDmsValue(coordinates.lng, "lng", 2);
|
||
}
|
||
return coordinateSystems.format(latlng.lat, latlng.lng, system.id, {
|
||
includeSystem: true,
|
||
precision: 6
|
||
});
|
||
};
|
||
|
||
const syncCoordinateReadoutFormat = () => {
|
||
if (!coordinateReadoutFormatButton) return;
|
||
const system = coordinateSystems
|
||
? coordinateSystems.getSystem(selectedCoordinateSystem)
|
||
: { id: "wgs84" };
|
||
const projected = system.id === "webmercator";
|
||
const dms = coordinateReadoutFormat === "dms";
|
||
coordinateReadoutFormatButton.disabled = projected;
|
||
coordinateReadoutFormatButton.textContent = projected ? "米制" : dms ? "度分秒" : "小数";
|
||
coordinateReadoutFormatButton.title = projected
|
||
? "Web 墨卡托坐标使用米制,不适用小数/度分秒切换。"
|
||
: "当前:" + (dms ? "度分秒" : "小数") + ";点击切换坐标格式。";
|
||
coordinateReadoutFormatButton.setAttribute(
|
||
"aria-pressed",
|
||
String(!projected && dms)
|
||
);
|
||
coordinateReadoutFormatButton.setAttribute(
|
||
"aria-label",
|
||
coordinateReadoutFormatButton.title
|
||
);
|
||
};
|
||
|
||
const setCoordinateReadoutFormat = (format, options = {}) => {
|
||
coordinateReadoutFormat = format === "dms" ? "dms" : "decimal";
|
||
syncCoordinateReadoutFormat();
|
||
updateReadout();
|
||
if (options.persist !== false) scheduleWorkspaceSave();
|
||
};
|
||
|
||
const updateReadout = (latlng) => {
|
||
const center = latlng || map.getCenter();
|
||
coordReadout.textContent = formatCoordinateReadout(center);
|
||
zoomReadout.textContent = "Z " + map.getZoom();
|
||
baseReadout.textContent = providerLabels[currentBaseKey];
|
||
};
|
||
|
||
const setCoordinateSystem = (requestedSystem, options = {}) => {
|
||
if (!coordinateSystems) return;
|
||
const system = coordinateSystems.getSystem(requestedSystem);
|
||
selectedCoordinateSystem = system.id;
|
||
if (coordinateSystemSelect) {
|
||
coordinateSystemSelect.value = system.id;
|
||
coordinateSystemSelect.title = system.description + " · " + system.epsg;
|
||
}
|
||
document.documentElement.dataset.coordinateSystem = system.id;
|
||
syncCoordinateReadoutFormat();
|
||
syncGridCoordinateUi();
|
||
map.closePopup();
|
||
updateReadout();
|
||
if (options.rerender !== false) renderDrawingList();
|
||
if (options.updatePrint !== false && typeof updatePrintDecor === "function") {
|
||
updatePrintDecor();
|
||
}
|
||
if (options.persist !== false) scheduleWorkspaceSave();
|
||
if (options.notify) {
|
||
showToast(
|
||
"坐标显示已切换为 " + system.label + "。" +
|
||
(system.approximate ? " 该基准采用公开近似转换参数。" : "")
|
||
);
|
||
}
|
||
};
|
||
|
||
coordinateSystemSelect?.addEventListener("change", (event) => {
|
||
setCoordinateSystem(event.target.value, { notify: true });
|
||
});
|
||
coordinateReadoutFormatButton?.addEventListener("click", () => {
|
||
setCoordinateReadoutFormat(
|
||
coordinateReadoutFormat === "dms" ? "decimal" : "dms",
|
||
{ persist: true }
|
||
);
|
||
});
|
||
setCoordinateSystem(selectedCoordinateSystem, {
|
||
persist: false,
|
||
rerender: false,
|
||
updatePrint: false,
|
||
notify: false
|
||
});
|
||
|
||
const tdtOverlayLayers = {
|
||
tdtVectorLabelToggle: tdtVectorLabelLayer,
|
||
tdtTerrainLabelToggle: tdtTerrainLabelLayer,
|
||
tdtImageryLabelToggle: tdtImageryLabelLayer,
|
||
tdtBoundaryToggle: tdtBoundaryLayer
|
||
};
|
||
const tdtLabelToggleIds = [
|
||
"tdtVectorLabelToggle",
|
||
"tdtTerrainLabelToggle",
|
||
"tdtImageryLabelToggle"
|
||
];
|
||
const tdtLabelToggleByBase = {
|
||
"tdt-vec": "tdtVectorLabelToggle",
|
||
"tdt-ter": "tdtTerrainLabelToggle",
|
||
"tdt-img": "tdtImageryLabelToggle"
|
||
};
|
||
|
||
const syncTdtOverlayLayers = () => {
|
||
Object.entries(tdtOverlayLayers).forEach(([toggleId, layer]) => {
|
||
const enabled = document.getElementById(toggleId)?.checked;
|
||
if (enabled && !map.hasLayer(layer)) layer.addTo(map);
|
||
if (!enabled && map.hasLayer(layer)) map.removeLayer(layer);
|
||
});
|
||
};
|
||
|
||
const selectTdtLabelForBase = (baseKey, options = {}) => {
|
||
const matchingToggle = tdtLabelToggleByBase[baseKey] || null;
|
||
if (options.force && !matchingToggle) return;
|
||
const checked = tdtLabelToggleIds.filter(
|
||
(id) => document.getElementById(id).checked
|
||
);
|
||
const selected = options.force && matchingToggle
|
||
? matchingToggle
|
||
: (matchingToggle && checked.includes(matchingToggle) ? matchingToggle : checked[0] || null);
|
||
tdtLabelToggleIds.forEach((id) => {
|
||
document.getElementById(id).checked = id === selected;
|
||
});
|
||
syncTdtOverlayLayers();
|
||
};
|
||
|
||
const setBase = (requestedKey, options) => {
|
||
const key = requestedKey === "relief" ? "standard" : requestedKey;
|
||
if (!baseLayers[key]) return;
|
||
if (requestedKey === "relief") {
|
||
document.getElementById("hillshadeToggle").checked = true;
|
||
}
|
||
Object.keys(baseLayers).forEach((baseKey) => {
|
||
if (map.hasLayer(baseLayers[baseKey])) map.removeLayer(baseLayers[baseKey]);
|
||
});
|
||
if (map.hasLayer(cleanLabelLayer)) map.removeLayer(cleanLabelLayer);
|
||
|
||
currentBaseKey = key;
|
||
baseLayers[key].addTo(map);
|
||
if (key === "clean") cleanLabelLayer.addTo(map);
|
||
syncTdtOverlayLayers();
|
||
baseLayers[key].bringToBack();
|
||
|
||
if (map.hasLayer(contourTerrainLayer)) map.removeLayer(contourTerrainLayer);
|
||
if (map.hasLayer(hillshadeTerrainLayer)) map.removeLayer(hillshadeTerrainLayer);
|
||
if (document.getElementById("hillshadeToggle").checked) map.addLayer(hillshadeTerrainLayer);
|
||
if (document.getElementById("contourToggle").checked) map.addLayer(contourTerrainLayer);
|
||
|
||
|
||
document.querySelectorAll(".base-card").forEach((button) => {
|
||
button.classList.toggle("active", button.dataset.base === key);
|
||
});
|
||
|
||
|
||
if (!options || !options.silent) {
|
||
setStatus("已切换为" + providerLabels[key], "busy");
|
||
window.setTimeout(() => setStatus("地图已就绪"), 700);
|
||
}
|
||
updateLegendVisibility();
|
||
updateReadout();
|
||
};
|
||
|
||
const railCategoryLabels = {
|
||
main: "主线",
|
||
highSpeed: "高速 / 客运专线",
|
||
branch: "支线 / 专用线",
|
||
yard: "站场",
|
||
depot: "车辆段 / 停车场",
|
||
siding: "侧线",
|
||
crossover: "渡线",
|
||
connection: "联络线",
|
||
test: "试车线",
|
||
loop: "环线",
|
||
freight: "货运 / 工业线",
|
||
other: "其他铁路"
|
||
};
|
||
|
||
const createRailPopup = (properties, type) => {
|
||
const name = properties.name || (type === "metro" ? "地铁线路" : "铁路线路");
|
||
const fields = [];
|
||
fields.push("分类:" + railCategoryLabels[railCategoryForTags(properties)]);
|
||
if (properties.ref) fields.push("线路编号:" + properties.ref);
|
||
if (properties.operator) fields.push("运营方:" + properties.operator);
|
||
if (properties.electrified) fields.push("电气化:" + properties.electrified);
|
||
return "<strong>" + escapeHtml(name) + "</strong>" +
|
||
(fields.length ? "<br>" + fields.map(escapeHtml).join("<br>") : "");
|
||
};
|
||
|
||
function escapeHtml(value) {
|
||
return String(value).replace(/[&<>"']/g, (char) => ({
|
||
"&": "&",
|
||
"<": "<",
|
||
">": ">",
|
||
"\"": """,
|
||
"'": "'"
|
||
})[char]);
|
||
}
|
||
|
||
const fetchWithTimeout = async (url, options, timeoutMs) => {
|
||
const controller = new AbortController();
|
||
const timer = window.setTimeout(() => controller.abort(), timeoutMs);
|
||
try {
|
||
return await fetch(url, Object.assign({}, options, { signal: controller.signal }));
|
||
} finally {
|
||
window.clearTimeout(timer);
|
||
}
|
||
};
|
||
|
||
const railCategoryForTags = (tags = {}) => {
|
||
const name = String(tags.name || "");
|
||
const service = String(tags.service || "");
|
||
const usage = String(tags.usage || "");
|
||
const trafficMode = String(tags["railway:traffic_mode"] || "");
|
||
if (usage === "test" || service === "test" || name.includes("试车") || name.includes("试验")) {
|
||
return "test";
|
||
}
|
||
if (service === "loop" || name.includes("环线")) return "loop";
|
||
if (
|
||
name.includes("车辆段") ||
|
||
name.includes("停车场") ||
|
||
name.includes("检修段") ||
|
||
name.includes("维修段")
|
||
) {
|
||
return "depot";
|
||
}
|
||
if (
|
||
service === "yard" ||
|
||
name.includes("站场")
|
||
) {
|
||
return "yard";
|
||
}
|
||
if (service === "siding") return "siding";
|
||
if (service === "crossover") return "crossover";
|
||
if (name.includes("联络")) {
|
||
return "connection";
|
||
}
|
||
if (
|
||
service === "spur" ||
|
||
usage === "branch" ||
|
||
name.includes("支线") ||
|
||
name.includes("专用线")
|
||
) {
|
||
return "branch";
|
||
}
|
||
if (
|
||
["freight", "industrial", "military"].includes(usage) ||
|
||
trafficMode === "freight"
|
||
) {
|
||
return "freight";
|
||
}
|
||
if (
|
||
String(tags.highspeed || "").toLowerCase() === "yes" ||
|
||
name.includes("客专") ||
|
||
name.includes("高铁") ||
|
||
name.includes("高速铁路") ||
|
||
name.includes("城际")
|
||
) {
|
||
return "highSpeed";
|
||
}
|
||
if (!service && (!usage || usage === "main")) return "main";
|
||
if (!service && usage === "passenger") return "main";
|
||
if (!service && tags.railway) return "main";
|
||
if (!service && !usage) return "main";
|
||
return "other";
|
||
};
|
||
|
||
const railCategoryKeys = [
|
||
"main",
|
||
"highSpeed",
|
||
"branch",
|
||
"yard",
|
||
"depot",
|
||
"siding",
|
||
"crossover",
|
||
"connection",
|
||
"test",
|
||
"loop",
|
||
"freight",
|
||
"other"
|
||
];
|
||
const nationalRailCategoryToggleIds = Object.fromEntries(
|
||
railCategoryKeys.map((key) => [
|
||
key,
|
||
"nationalRail" + key.charAt(0).toUpperCase() + key.slice(1) + "CategoryToggle"
|
||
])
|
||
);
|
||
const metroRailCategoryToggleIds = Object.fromEntries(
|
||
railCategoryKeys.map((key) => [
|
||
key,
|
||
"metroRail" + key.charAt(0).toUpperCase() + key.slice(1) + "CategoryToggle"
|
||
])
|
||
);
|
||
|
||
const railCategoryAllowed = (tags, isMetro) => {
|
||
const category = railCategoryForTags(tags);
|
||
const toggleIds = isMetro
|
||
? metroRailCategoryToggleIds
|
||
: nationalRailCategoryToggleIds;
|
||
return document.getElementById(toggleIds[category]).checked;
|
||
};
|
||
|
||
const renderRailElements = (elements, options = {}) => {
|
||
const replace = options.replace !== false;
|
||
if (replace) {
|
||
nationalRailGroup.clearLayers();
|
||
metroGroup.clearLayers();
|
||
renderedRailFeatureIds = new Set();
|
||
}
|
||
|
||
let nationalCount = 0;
|
||
let metroCount = 0;
|
||
const seenWayIds = new Set();
|
||
const urbanRailKinds = new Set(["subway", "light_rail", "monorail"]);
|
||
const urbanRouteKinds = new Set(["subway", "light_rail", "monorail"]);
|
||
const segments = [];
|
||
|
||
const addSegment = (geometry, tags, wayId) => {
|
||
if (!Array.isArray(geometry) || geometry.length < 2) return;
|
||
if (wayId && seenWayIds.has(wayId)) return;
|
||
if (wayId) seenWayIds.add(wayId);
|
||
segments.push({ geometry, tags: tags || {}, id: wayId });
|
||
};
|
||
|
||
// Direct way results carry the most reliable railway tags. Relation members
|
||
// are added afterwards to fill gaps between ways split at stations/junctions.
|
||
elements.forEach((element) => {
|
||
if (element.type === "relation" || !Array.isArray(element.geometry)) return;
|
||
addSegment(element.geometry, element.tags, element.id);
|
||
});
|
||
elements.forEach((element) => {
|
||
if (element.type !== "relation" || !Array.isArray(element.members)) return;
|
||
const routeKind = element.tags && element.tags.route;
|
||
if (!urbanRouteKinds.has(routeKind)) return;
|
||
element.members.forEach((member) => {
|
||
if (member.type !== "way" || !Array.isArray(member.geometry)) return;
|
||
if (["platform", "platform_edge", "stop", "stop_area"].includes(member.role)) return;
|
||
addSegment(member.geometry, element.tags, member.ref);
|
||
});
|
||
});
|
||
|
||
segments.forEach(({ geometry, tags, id }) => {
|
||
if (id && renderedRailFeatureIds.has(id)) return;
|
||
const railwayKind = tags.railway || tags.route || "";
|
||
const isMetro = urbanRailKinds.has(railwayKind) || urbanRouteKinds.has(tags.route);
|
||
if (!railCategoryAllowed(tags, isMetro)) return;
|
||
const latlngs = geometry.map((point) => [point.lat, point.lon]);
|
||
const railStyle = isMetro ? metroLineStyle : railwayLineStyle;
|
||
let railLayer;
|
||
if (railStyle === "railway") {
|
||
const blackBase = L.polyline(latlngs, {
|
||
color: "#111",
|
||
weight: isMetro ? 3.4 : 3.8,
|
||
opacity: 0.94,
|
||
lineCap: "butt",
|
||
lineJoin: "round"
|
||
});
|
||
const whiteSegments = L.polyline(latlngs, {
|
||
color: "#fff",
|
||
weight: 1.9,
|
||
opacity: 0.98,
|
||
dashArray: "7 7",
|
||
lineCap: "butt",
|
||
lineJoin: "butt",
|
||
interactive: false
|
||
});
|
||
blackBase.bindPopup(createRailPopup(tags, isMetro ? "metro" : "national"));
|
||
railLayer = L.featureGroup([blackBase, whiteSegments]);
|
||
} else {
|
||
const line = L.polyline(latlngs, {
|
||
color: isMetro ? themeColors.metro : themeColors.national,
|
||
weight: isMetro ? 2.2 : 2.6,
|
||
opacity: isMetro ? 0.88 : 0.9,
|
||
lineCap: "round",
|
||
lineJoin: "round"
|
||
});
|
||
line.bindPopup(createRailPopup(tags, isMetro ? "metro" : "national"));
|
||
railLayer = line;
|
||
}
|
||
(isMetro ? metroGroup : nationalRailGroup).addLayer(railLayer);
|
||
if (id) renderedRailFeatureIds.add(id);
|
||
if (isMetro) metroCount += 1;
|
||
else nationalCount += 1;
|
||
});
|
||
|
||
return { nationalCount, metroCount };
|
||
};
|
||
|
||
const ensureLocalRailFallback = () => {
|
||
const local = window.MAP_STUDIO_LOCAL_RAILS;
|
||
const nationalOn = document.getElementById("nationalRailToggle").checked;
|
||
const metroOn = document.getElementById("metroToggle").checked;
|
||
if (!local || (!nationalOn && !metroOn)) return null;
|
||
|
||
const bounds = map.getBounds().pad(0.04);
|
||
const localBounds = (() => {
|
||
let south = Infinity;
|
||
let west = Infinity;
|
||
let north = -Infinity;
|
||
let east = -Infinity;
|
||
[local.national?.features, local.subway?.features].forEach((features) => {
|
||
(features || []).forEach((feature) => {
|
||
(feature.geometry?.coordinates || []).forEach((coordinate) => {
|
||
if (!Array.isArray(coordinate) || coordinate.length < 2) return;
|
||
west = Math.min(west, Number(coordinate[0]));
|
||
south = Math.min(south, Number(coordinate[1]));
|
||
east = Math.max(east, Number(coordinate[0]));
|
||
north = Math.max(north, Number(coordinate[1]));
|
||
});
|
||
});
|
||
});
|
||
if ([south, west, north, east].every(Number.isFinite)) {
|
||
return L.latLngBounds([south, west], [north, east]);
|
||
}
|
||
return L.latLngBounds(
|
||
[local.bbox[0], local.bbox[1]],
|
||
[local.bbox[2], local.bbox[3]]
|
||
);
|
||
})();
|
||
if (!bounds.intersects(localBounds)) return null;
|
||
const viewKey = bounds.toBBoxString();
|
||
if (localRailRendered && viewKey === localRailViewKey) {
|
||
return {
|
||
nationalCount: nationalRailGroup.getLayers().length,
|
||
metroCount: metroGroup.getLayers().length
|
||
};
|
||
}
|
||
|
||
const visibleFeatures = (features) => (features || []).filter((feature) =>
|
||
(feature.geometry?.coordinates || []).some((coordinate) =>
|
||
bounds.contains(L.latLng(coordinate[1], coordinate[0]))
|
||
)
|
||
);
|
||
const toElements = (features) => features.map((feature) => ({
|
||
tags: feature.properties || {},
|
||
geometry: feature.geometry.coordinates.map((coordinate) => ({
|
||
lat: coordinate[1],
|
||
lon: coordinate[0]
|
||
}))
|
||
}));
|
||
const hasRemoteNational = nationalRailGroup.getLayers().length > 0;
|
||
const hasRemoteMetro = metroGroup.getLayers().length > 0;
|
||
const nationalFeatures = nationalOn && !hasRemoteNational
|
||
? visibleFeatures(local.national?.features)
|
||
: [];
|
||
const subwayFeatures = metroOn && (
|
||
!hasRemoteMetro ||
|
||
map.getZoom() < 9 ||
|
||
metroGroup.getLayers().length < 100
|
||
)
|
||
? visibleFeatures(local.subway?.features)
|
||
: [];
|
||
if (!nationalFeatures.length && !subwayFeatures.length) return null;
|
||
|
||
const fallbackElements = [
|
||
...toElements(nationalFeatures),
|
||
...toElements(subwayFeatures)
|
||
];
|
||
loadedRailElements.push(...fallbackElements);
|
||
const counts = renderRailElements(fallbackElements, { replace: false });
|
||
localRailRendered = true;
|
||
localRailViewKey = viewKey;
|
||
railStatus.textContent =
|
||
"已合并内置北京完整地铁数据(新增 " + counts.metroCount + " 段)。";
|
||
return {
|
||
nationalCount: nationalRailGroup.getLayers().length,
|
||
metroCount: metroGroup.getLayers().length
|
||
};
|
||
};
|
||
|
||
const getViewportBlocks = () => {
|
||
const pixelBounds = map.getPixelBounds();
|
||
const pixelWidth = pixelBounds.max.x - pixelBounds.min.x;
|
||
const pixelHeight = pixelBounds.max.y - pixelBounds.min.y;
|
||
let blockSize = 512;
|
||
while (
|
||
Math.ceil((pixelWidth + blockSize) / blockSize) *
|
||
Math.ceil((pixelHeight + blockSize) / blockSize) > 16
|
||
) {
|
||
blockSize *= 2;
|
||
}
|
||
const zoom = map.getZoom();
|
||
const blocks = [];
|
||
const startX = Math.floor(pixelBounds.min.x / blockSize) * blockSize;
|
||
const startY = Math.floor(pixelBounds.min.y / blockSize) * blockSize;
|
||
for (let y = startY; y <= pixelBounds.max.y; y += blockSize) {
|
||
for (let x = startX; x <= pixelBounds.max.x; x += blockSize) {
|
||
const northwest = map.unproject(L.point(x, y), zoom);
|
||
const southeast = map.unproject(L.point(x + blockSize, y + blockSize), zoom);
|
||
blocks.push(L.latLngBounds(northwest, southeast));
|
||
}
|
||
}
|
||
return blocks;
|
||
};
|
||
|
||
const waitForDataJob = async (kind, cacheKey, isCurrent) => {
|
||
for (let attempt = 0; attempt < 90; attempt += 1) {
|
||
await new Promise((resolve) => window.setTimeout(resolve, 2000));
|
||
if (!isCurrent()) return false;
|
||
try {
|
||
const response = await fetchWithTimeout(
|
||
mapServiceUrl("api/" + kind + "/status?key=" + encodeURIComponent(cacheKey)),
|
||
{ headers: { Accept: "application/json" } },
|
||
10000
|
||
);
|
||
if (!response.ok) continue;
|
||
const status = await response.json();
|
||
if (status.ready) return true;
|
||
} catch (error) {
|
||
// Keep polling; the server may still be downloading in the background.
|
||
}
|
||
}
|
||
return false;
|
||
};
|
||
|
||
const decodeTransferElements = (data, kind, group = "elements") => {
|
||
const elements = data[group] || [];
|
||
if (data.format !== "delta-v1") return elements;
|
||
return elements.map((element) => {
|
||
const values = element.g || [];
|
||
if (values.length < (kind === "port" ? 2 : 4) || values.length % 2 !== 0) return null;
|
||
let lat = values[0];
|
||
let lon = values[1];
|
||
const geometry = [{ lat: lat / 10000000, lon: lon / 10000000 }];
|
||
for (let index = 2; index < values.length; index += 2) {
|
||
lat += values[index];
|
||
lon += values[index + 1];
|
||
geometry.push({ lat: lat / 10000000, lon: lon / 10000000 });
|
||
}
|
||
if (kind === "rail") {
|
||
const tags = { railway: element.r };
|
||
if (element.n) tags.name = element.n;
|
||
if (element.f) tags.ref = element.f;
|
||
if (element.o) tags.operator = element.o;
|
||
if (element.e) tags.electrified = element.e;
|
||
return { type: "way", id: element.i, tags, geometry };
|
||
}
|
||
if (kind === "boundary") {
|
||
const tags = {
|
||
boundary: "administrative",
|
||
admin_level: Number(element.a) || 6
|
||
};
|
||
if (element.n) tags.name = element.n;
|
||
if (element.d) tags.disputed = true;
|
||
return { type: "way", id: element.i, tags, geometry };
|
||
}
|
||
let tags;
|
||
if (kind === "port") {
|
||
tags = { port: element.p || "port" };
|
||
} else if (kind === "vegetation") {
|
||
tags = { vegetation: element.v || "vegetation" };
|
||
} else {
|
||
tags = element.k === "L"
|
||
? { waterway: element.w }
|
||
: { natural: "water", water: element.w };
|
||
}
|
||
if (element.n) tags.name = element.n;
|
||
return {
|
||
type: kind === "port" && geometry.length === 1 ? "point" : "way",
|
||
id: element.i,
|
||
tags,
|
||
geometry
|
||
};
|
||
}).filter(Boolean);
|
||
};
|
||
|
||
const localVectorSelectedGroups = () => new Set(
|
||
Array.from(document.querySelectorAll(".local-vector-layer-toggle:checked"))
|
||
.map((input) => input.value)
|
||
);
|
||
|
||
const lonToVectorTile = (lon, z) => {
|
||
const count = Math.pow(2, z);
|
||
return Math.max(0, Math.min(count - 1, Math.floor((lon + 180) / 360 * count)));
|
||
};
|
||
|
||
const latToVectorTile = (lat, z) => {
|
||
const count = Math.pow(2, z);
|
||
const clipped = Math.max(-85.05112878, Math.min(85.05112878, lat));
|
||
const radians = clipped * Math.PI / 180;
|
||
return Math.max(
|
||
0,
|
||
Math.min(count - 1, Math.floor((1 - Math.asinh(Math.tan(radians)) / Math.PI) / 2 * count))
|
||
);
|
||
};
|
||
|
||
const localVectorStyle = (feature) => {
|
||
const group = feature.properties?.group || "";
|
||
const geometryType = feature.geometry?.type || "";
|
||
const isArea = geometryType.includes("Polygon");
|
||
if (group === "roads") {
|
||
const grade = String(feature.properties?.rteg || "");
|
||
if (grade.includes("高速")) {
|
||
return { color: themeColors.localRoads, weight: 2.7, opacity: 0.95 };
|
||
}
|
||
if (grade.includes("一级")) {
|
||
return { color: themeColors.localRoads, weight: 2.1, opacity: 0.92 };
|
||
}
|
||
if (grade.includes("二级")) {
|
||
return { color: themeColors.localRoads, weight: 1.55, opacity: 0.9 };
|
||
}
|
||
return { color: themeColors.localRoads, weight: 1, opacity: 0.82 };
|
||
}
|
||
if (group === "railways") {
|
||
return railwayLineStyle === "railway"
|
||
? { color: "#111", weight: 3.4, opacity: 0.96 }
|
||
: { color: themeColors.localRailways, weight: 2.1, opacity: 0.94 };
|
||
}
|
||
if (group === "water") {
|
||
return isArea
|
||
? { color: themeColors.localWater, weight: 1, opacity: 0.9, fillColor: themeColors.localWater, fillOpacity: 0.26 }
|
||
: { color: themeColors.localWater, weight: 1.45, opacity: 0.9 };
|
||
}
|
||
if (group === "province") {
|
||
return {
|
||
color: boundaryConfig.highColor,
|
||
weight: 2.8,
|
||
opacity: 0.97,
|
||
fillColor: boundaryConfig.highColor,
|
||
fillOpacity: isArea ? 0.02 : 0
|
||
};
|
||
}
|
||
if (group === "city") {
|
||
return {
|
||
color: boundaryConfig.middleColor,
|
||
weight: 2,
|
||
opacity: 0.94,
|
||
fillColor: boundaryConfig.middleColor,
|
||
fillOpacity: isArea ? 0.018 : 0
|
||
};
|
||
}
|
||
if (group === "county") {
|
||
return {
|
||
color: boundaryConfig.localColor,
|
||
weight: 1.25,
|
||
opacity: 0.9,
|
||
dashArray: "6 4",
|
||
fillColor: boundaryConfig.localColor,
|
||
fillOpacity: isArea ? 0.012 : 0
|
||
};
|
||
}
|
||
if (group === "administration") {
|
||
return {
|
||
color: themeColors.localAdministration,
|
||
weight: 1.9,
|
||
opacity: 0.92,
|
||
fillColor: themeColors.localAdministration,
|
||
fillOpacity: isArea ? 0.18 : 0
|
||
};
|
||
}
|
||
if (group === "settlements") {
|
||
return {
|
||
color: themeColors.localSettlements,
|
||
weight: 1,
|
||
opacity: 0.78,
|
||
fillColor: themeColors.localSettlements,
|
||
fillOpacity: isArea ? 0.2 : 0
|
||
};
|
||
}
|
||
if (group === "vegetation") {
|
||
return {
|
||
color: themeColors.localVegetation,
|
||
weight: 1,
|
||
opacity: 0.72,
|
||
fillColor: themeColors.localVegetation,
|
||
fillOpacity: isArea ? 0.2 : 0
|
||
};
|
||
}
|
||
if (group === "terrain") {
|
||
return { color: themeColors.localTerrain, weight: 1, opacity: 0.72, dashArray: "5 4" };
|
||
}
|
||
if (group === "heritage") {
|
||
return { color: themeColors.localHeritage, weight: 1.5, opacity: 0.86 };
|
||
}
|
||
return {
|
||
color: themeColors.localFacilities,
|
||
weight: 1.2,
|
||
opacity: 0.82,
|
||
fillColor: themeColors.localFacilities,
|
||
fillOpacity: isArea ? 0.18 : 0
|
||
};
|
||
};
|
||
|
||
const localVectorPointStyle = (feature) => {
|
||
const group = feature.properties?.group || "";
|
||
if (group === "railways") {
|
||
return {
|
||
radius: 3,
|
||
color: "#fff",
|
||
weight: 1,
|
||
fillColor: railwayLineStyle === "railway" ? "#111" : themeColors.localRailways,
|
||
fillOpacity: 1
|
||
};
|
||
}
|
||
if (group === "water") {
|
||
return { radius: 2.5, color: "#fff", weight: 1, fillColor: themeColors.localWater, fillOpacity: 1 };
|
||
}
|
||
if (group === "settlements") {
|
||
return { radius: 2, color: "#fff", weight: 0.7, fillColor: themeColors.localSettlements, fillOpacity: 0.9 };
|
||
}
|
||
if (group === "heritage") {
|
||
return { radius: 3, color: "#fff", weight: 1, fillColor: themeColors.localHeritage, fillOpacity: 1 };
|
||
}
|
||
return { radius: 2.2, color: "#fff", weight: 0.7, fillColor: "#7b7468", fillOpacity: 0.9 };
|
||
};
|
||
|
||
const renderLocalVectorFeatures = (features) => {
|
||
localVectorLayer.clearLayers();
|
||
const selected = localVectorSelectedGroups();
|
||
const counts = {};
|
||
const fillAndPointOnlyGroups = new Set([
|
||
"administration",
|
||
"settlements",
|
||
"vegetation",
|
||
"facilities"
|
||
]);
|
||
const seenPoints = new Set();
|
||
const groupAliases = {
|
||
"省": "province",
|
||
"市": "city",
|
||
"县": "county"
|
||
};
|
||
const visible = features.filter((feature) => {
|
||
const properties = feature.properties || {};
|
||
const group = groupAliases[properties.group] || properties.group;
|
||
if (!selected.has(group)) return false;
|
||
const geometryType = feature.geometry?.type || "";
|
||
const layerCode = String(properties.layer || "");
|
||
const isPolygon = geometryType.includes("Polygon");
|
||
const isLine = geometryType.includes("Line");
|
||
const isPoint = geometryType === "Point" || geometryType === "MultiPoint";
|
||
if (/A$/.test(layerCode) && !isPolygon) return false;
|
||
if (/L$/.test(layerCode) && !isLine) return false;
|
||
if (/P$/.test(layerCode) && !isPoint) return false;
|
||
if (isPoint) {
|
||
const pointKey = [
|
||
group,
|
||
layerCode,
|
||
properties.name || "",
|
||
JSON.stringify(feature.geometry?.coordinates)
|
||
].join("|");
|
||
if (seenPoints.has(pointKey)) return false;
|
||
seenPoints.add(pointKey);
|
||
}
|
||
if (
|
||
fillAndPointOnlyGroups.has(group) &&
|
||
!isPolygon &&
|
||
!isPoint
|
||
) {
|
||
return false;
|
||
}
|
||
if (
|
||
properties.role === "outline" &&
|
||
!["province", "city", "county"].includes(group)
|
||
) {
|
||
return false;
|
||
}
|
||
counts[group] = (counts[group] || 0) + 1;
|
||
return true;
|
||
});
|
||
if (!visible.length || !document.getElementById("localVectorToggle").checked) return counts;
|
||
const labeledAdministrativeAreas = new Set();
|
||
const localRailOverlays = [];
|
||
const geoJsonLayer = L.geoJSON(
|
||
{ type: "FeatureCollection", features: visible },
|
||
{
|
||
pane: "localVectorPane",
|
||
interactive: false,
|
||
style: (feature) => ({
|
||
...localVectorStyle(feature),
|
||
stroke: !(feature.geometry?.type || "").includes("Polygon"),
|
||
fill: (feature.geometry?.type || "").includes("Polygon")
|
||
}),
|
||
pointToLayer: (feature, latlng) => L.circleMarker(
|
||
latlng,
|
||
{ ...localVectorPointStyle(feature), pane: "localVectorPane", interactive: false }
|
||
),
|
||
onEachFeature: (feature, layer) => {
|
||
const properties = feature.properties || {};
|
||
if (
|
||
properties.group === "railways" &&
|
||
railwayLineStyle === "railway" &&
|
||
layer instanceof L.Polyline
|
||
) {
|
||
localRailOverlays.push(
|
||
L.polyline(layer.getLatLngs(), {
|
||
pane: "localVectorPane",
|
||
color: "#fff",
|
||
weight: 1.5,
|
||
opacity: 0.98,
|
||
dashArray: "7 7",
|
||
lineCap: "butt",
|
||
interactive: false
|
||
})
|
||
);
|
||
}
|
||
if (
|
||
properties.group === "administration" &&
|
||
(feature.geometry?.type || "").includes("Polygon") &&
|
||
properties.name
|
||
) {
|
||
const labelKey = String(feature.id || properties.name).replace(/:[ao]\d+$/, "");
|
||
if (labeledAdministrativeAreas.has(labelKey)) return;
|
||
labeledAdministrativeAreas.add(labelKey);
|
||
layer.bindTooltip(escapeHtml(properties.name), {
|
||
permanent: true,
|
||
direction: "center",
|
||
className: "local-vector-admin-label",
|
||
opacity: 0.94,
|
||
interactive: false
|
||
});
|
||
}
|
||
}
|
||
}
|
||
);
|
||
localVectorLayer.addLayer(geoJsonLayer);
|
||
localRailOverlays.forEach((overlay) => localVectorLayer.addLayer(overlay));
|
||
return counts;
|
||
};
|
||
|
||
const updateLocalVectorStatus = (counts, prefix) => {
|
||
if (!localVectorStatus) return;
|
||
const labels = {
|
||
roads: "道路",
|
||
railways: "铁路",
|
||
water: "水系",
|
||
administration: "行政",
|
||
province: "省界",
|
||
city: "市界",
|
||
county: "区县界",
|
||
settlements: "居民地",
|
||
vegetation: "植被",
|
||
terrain: "地形",
|
||
facilities: "设施",
|
||
heritage: "古迹"
|
||
};
|
||
const details = Object.entries(counts)
|
||
.filter(([, count]) => count > 0)
|
||
.map(([group, count]) => labels[group] + " " + count);
|
||
const total = Object.values(counts).reduce((sum, count) => sum + count, 0);
|
||
localVectorStatus.textContent = total
|
||
? prefix + " · " + details.join(" · ")
|
||
: prefix + " · 当前视窗没有可显示的选中类别";
|
||
};
|
||
|
||
const ensureLocalVectorManifest = async () => {
|
||
if (localVectorManifest) return localVectorManifest;
|
||
const response = await fetchWithTimeout(
|
||
mapServiceUrl("api/local-vector/status"),
|
||
{ headers: { Accept: "application/json" }, cache: "no-store" },
|
||
15000
|
||
);
|
||
const manifest = await response.json().catch(() => ({}));
|
||
if (!response.ok || !manifest.available) {
|
||
throw new Error(manifest.message || "本地矢量瓦片尚未生成");
|
||
}
|
||
if (localVectorManifest?.generatedAt !== manifest.generatedAt) {
|
||
localVectorMissingTiles = new Set();
|
||
}
|
||
localVectorManifest = manifest;
|
||
return manifest;
|
||
};
|
||
|
||
const ensureLocalVector25Manifest = async () => {
|
||
if (localVector25Manifest) return localVector25Manifest;
|
||
const response = await fetchWithTimeout(
|
||
mapServiceUrl("api/local-vector-25/status"),
|
||
{ headers: { Accept: "application/json" }, cache: "no-store" },
|
||
15000
|
||
);
|
||
const manifest = await response.json().catch(() => ({}));
|
||
if (!response.ok || !manifest.available) return null;
|
||
localVector25MissingTiles = new Set();
|
||
localVector25Manifest = manifest;
|
||
return manifest;
|
||
};
|
||
|
||
const loadLocalVectorData = async () => {
|
||
const toggle = document.getElementById("localVectorToggle");
|
||
if (!toggle.checked) {
|
||
localVectorLoadSequence += 1;
|
||
localVectorFeatures = [];
|
||
localVectorDisplayedZoom = null;
|
||
localVectorLayer.clearLayers();
|
||
if (map.hasLayer(localVectorLayer)) map.removeLayer(localVectorLayer);
|
||
if (localVectorStatus) localVectorStatus.textContent = "开启后加载当前视窗的本地矢量数据。";
|
||
return;
|
||
}
|
||
if (!map.hasLayer(localVectorLayer)) localVectorLayer.addTo(map);
|
||
if (!localVectorSelectedGroups().size) {
|
||
localVectorFeatures = [];
|
||
localVectorLayer.clearLayers();
|
||
if (localVectorStatus) localVectorStatus.textContent = "请至少选择一种本地矢量类别。";
|
||
return;
|
||
}
|
||
const sequence = ++localVectorLoadSequence;
|
||
try {
|
||
const manifest = await ensureLocalVectorManifest();
|
||
const mapBounds = map.getBounds();
|
||
const extent = manifest.bounds;
|
||
const south = Math.max(mapBounds.getSouth(), extent[1]);
|
||
const west = Math.max(mapBounds.getWest(), extent[0]);
|
||
const north = Math.min(mapBounds.getNorth(), extent[3]);
|
||
const east = Math.min(mapBounds.getEast(), extent[2]);
|
||
if (!(south < north && west < east)) {
|
||
localVectorFeatures = [];
|
||
renderLocalVectorFeatures([]);
|
||
if (localVectorStatus) {
|
||
localVectorStatus.textContent =
|
||
"当前视窗不在本地图幅覆盖范围内(东经 " + extent[0] + "°–" + extent[2] +
|
||
"°、北纬 " + extent[1] + "°–" + extent[3] + "°)。";
|
||
}
|
||
return;
|
||
}
|
||
const targetZoom = Math.round(map.getZoom());
|
||
if (targetZoom < 3) {
|
||
localVectorFeatures = [];
|
||
renderLocalVectorFeatures([]);
|
||
if (localVectorStatus) {
|
||
localVectorStatus.textContent = "请放大到 Z3 以上加载天地图图素。";
|
||
}
|
||
return;
|
||
}
|
||
let preferred25Features = null;
|
||
let preferred25Zoom = null;
|
||
let preferred25Groups = new Set();
|
||
if (targetZoom >= 8) {
|
||
try {
|
||
const manifest25 = await ensureLocalVector25Manifest();
|
||
const selectedGroups = localVectorSelectedGroups();
|
||
if (manifest25) {
|
||
preferred25Groups = new Set(manifest25.groups || []);
|
||
const hasRelevantGroup = Array.from(selectedGroups).some(
|
||
(group) => preferred25Groups.has(group)
|
||
);
|
||
const extent25 = manifest25.bounds;
|
||
const south25 = Math.max(south, extent25[1]);
|
||
const west25 = Math.max(west, extent25[0]);
|
||
const north25 = Math.min(north, extent25[3]);
|
||
const east25 = Math.min(east, extent25[2]);
|
||
if (hasRelevantGroup && south25 < north25 && west25 < east25) {
|
||
const available25 = Object.keys(manifest25.tiles || {})
|
||
.map(Number)
|
||
.sort((a, b) => a - b);
|
||
if (!available25.length) throw new Error("No 1:250,000 tile levels");
|
||
const browseMax25 = Math.max(
|
||
Number(manifest25.maxZoom) || 12,
|
||
Number(manifest25.browseMaxZoom) || 12
|
||
);
|
||
const native25 = Math.min(browseMax25, targetZoom);
|
||
const coordinates25 = [];
|
||
const x0 = lonToVectorTile(west25, native25);
|
||
const x1 = lonToVectorTile(east25, native25);
|
||
const y0 = latToVectorTile(north25, native25);
|
||
const y1 = latToVectorTile(south25, native25);
|
||
for (let y = y0; y <= y1; y += 1) {
|
||
for (let x = x0; x <= x1; x += 1) coordinates25.push([x, y]);
|
||
}
|
||
const tiles25 = await Promise.all(coordinates25.map(async ([x, y]) => {
|
||
const version = encodeURIComponent(manifest25.generatedAt || "1");
|
||
const tileUrl = mapServiceUrl(
|
||
"api/local-vector-25/" + native25 + "/" + x + "/" + y +
|
||
".json?v=" + version
|
||
);
|
||
if (localVector25MissingTiles.has(tileUrl)) return null;
|
||
try {
|
||
const response = await fetchWithTimeout(
|
||
tileUrl,
|
||
{ headers: { Accept: "application/json" } },
|
||
45000
|
||
);
|
||
if (response.status === 404) {
|
||
localVector25MissingTiles.add(tileUrl);
|
||
return null;
|
||
}
|
||
if (!response.ok) return null;
|
||
const payload = await response.json();
|
||
return payload.features || [];
|
||
} catch (error) {
|
||
return null;
|
||
}
|
||
}));
|
||
if (tiles25.every((tile) => Array.isArray(tile))) {
|
||
const features25 = tiles25.flat();
|
||
if (features25.length) {
|
||
preferred25Features = features25;
|
||
preferred25Zoom = native25;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
} catch (error) {
|
||
preferred25Features = null;
|
||
}
|
||
}
|
||
const browseMax = Math.max(
|
||
Number(manifest.maxZoom) || 10,
|
||
Number(manifest.browseMaxZoom) || 10
|
||
);
|
||
const nativeZoom = Math.min(browseMax, targetZoom);
|
||
localVectorDisplayedZoom = nativeZoom;
|
||
const x0 = lonToVectorTile(west, nativeZoom);
|
||
const x1 = lonToVectorTile(east, nativeZoom);
|
||
const y0 = latToVectorTile(north, nativeZoom);
|
||
const y1 = latToVectorTile(south, nativeZoom);
|
||
const coordinates = [];
|
||
for (let y = y0; y <= y1; y += 1) {
|
||
for (let x = x0; x <= x1; x += 1) coordinates.push([x, y]);
|
||
}
|
||
if (localVectorStatus) {
|
||
localVectorStatus.textContent = "正在加载本地 Z" + nativeZoom + " 矢量瓦片…";
|
||
}
|
||
const tiles = await Promise.all(coordinates.map(async ([x, y]) => {
|
||
try {
|
||
const dataVersion = encodeURIComponent(manifest.generatedAt || "1");
|
||
const tileUrl = mapServiceUrl(
|
||
"api/local-vector/" + nativeZoom + "/" + x + "/" + y + ".json?v=" + dataVersion
|
||
);
|
||
if (localVectorMissingTiles.has(tileUrl)) return [];
|
||
const response = await fetchWithTimeout(
|
||
tileUrl,
|
||
{ headers: { Accept: "application/json" } },
|
||
45000
|
||
);
|
||
if (response.status === 404) {
|
||
localVectorMissingTiles.add(tileUrl);
|
||
return [];
|
||
}
|
||
if (!response.ok) throw new Error("HTTP " + response.status);
|
||
const payload = await response.json();
|
||
return payload.features || [];
|
||
} catch (error) {
|
||
return [];
|
||
}
|
||
}));
|
||
if (sequence !== localVectorLoadSequence || !toggle.checked) return;
|
||
const fallbackFeatures = tiles.flat();
|
||
let sourcePrefix = "本地 Z" + nativeZoom + " · " + coordinates.length + " 个瓦片";
|
||
if (preferred25Features) {
|
||
localVectorFeatures = [
|
||
...preferred25Features,
|
||
...fallbackFeatures.filter(
|
||
(feature) => !preferred25Groups.has(feature.properties?.group)
|
||
)
|
||
];
|
||
localVectorDisplayedZoom = preferred25Zoom;
|
||
sourcePrefix =
|
||
"1:25 万 Z" + preferred25Zoom + " + 1:100 万补充";
|
||
} else {
|
||
localVectorFeatures = fallbackFeatures;
|
||
localVectorDisplayedZoom = nativeZoom;
|
||
}
|
||
const counts = renderLocalVectorFeatures(localVectorFeatures);
|
||
updateLocalVectorStatus(counts, sourcePrefix);
|
||
} catch (error) {
|
||
if (sequence !== localVectorLoadSequence || !toggle.checked) return;
|
||
if (localVectorStatus) localVectorStatus.textContent = "本地矢量加载失败:" + error.message;
|
||
}
|
||
};
|
||
|
||
const administrativeBoundaryStyle = (adminLevel) => {
|
||
const level = Number(adminLevel) || 6;
|
||
if (level <= 4) {
|
||
return { color: boundaryConfig.highColor, weight: 3, opacity: 0.98, dashArray: null };
|
||
}
|
||
if (level <= 6) {
|
||
return { color: boundaryConfig.middleColor, weight: 2.3, opacity: 0.96, dashArray: null };
|
||
}
|
||
return { color: boundaryConfig.localColor, weight: 1.7, opacity: 0.94, dashArray: "6 4" };
|
||
};
|
||
|
||
const renderAdministrativeBoundaries = (elements) => {
|
||
lastAdministrativeBoundaryElements = elements;
|
||
administrativeBoundaryLayer.clearLayers();
|
||
const counts = { high: 0, middle: 0, local: 0 };
|
||
elements.forEach((element) => {
|
||
const geometry = element.geometry || [];
|
||
if (geometry.length < 2) return;
|
||
const level = Number(element.tags?.admin_level) || 6;
|
||
const style = administrativeBoundaryStyle(level);
|
||
const points = geometry.map((point) => [Number(point.lat), Number(point.lon)]);
|
||
administrativeBoundaryLayer.addLayer(
|
||
L.polyline(points, {
|
||
color: "#ffffff",
|
||
weight: style.weight + 2,
|
||
opacity: 0.72,
|
||
dashArray: null,
|
||
pane: "administrativeBoundaryPane",
|
||
interactive: false,
|
||
lineCap: "round",
|
||
lineJoin: "round"
|
||
})
|
||
);
|
||
administrativeBoundaryLayer.addLayer(
|
||
L.polyline(
|
||
points,
|
||
{
|
||
...style,
|
||
pane: "administrativeBoundaryPane",
|
||
interactive: false,
|
||
lineCap: "round",
|
||
lineJoin: "round"
|
||
}
|
||
)
|
||
);
|
||
if (level <= 4) counts.high += 1;
|
||
else if (level <= 6) counts.middle += 1;
|
||
else counts.local += 1;
|
||
});
|
||
return counts;
|
||
};
|
||
|
||
const applyAdministrativeBoundaryControls = () => {
|
||
boundaryConfig.highColor = document.getElementById("boundaryHighColor").value;
|
||
boundaryConfig.middleColor = document.getElementById("boundaryMiddleColor").value;
|
||
boundaryConfig.localColor = document.getElementById("boundaryLocalColor").value;
|
||
if (lastAdministrativeBoundaryElements.length) {
|
||
renderAdministrativeBoundaries(lastAdministrativeBoundaryElements);
|
||
}
|
||
if (localVectorFeatures.length && document.getElementById("localVectorToggle").checked) {
|
||
renderLocalVectorFeatures(localVectorFeatures);
|
||
}
|
||
updateLegendVisibility();
|
||
};
|
||
|
||
const loadAdministrativeBoundaryData = async () => {
|
||
const toggle = document.getElementById("tdtBoundaryToggle");
|
||
if (!toggle.checked) {
|
||
administrativeBoundaryLayer.clearLayers();
|
||
lastAdministrativeBoundaryElements = [];
|
||
if (map.hasLayer(administrativeBoundaryLayer)) map.removeLayer(administrativeBoundaryLayer);
|
||
if (boundaryStatus) boundaryStatus.textContent = "开启后加载当前视窗的省、地级和县级行政边界。";
|
||
return;
|
||
}
|
||
if (!map.hasLayer(administrativeBoundaryLayer)) administrativeBoundaryLayer.addTo(map);
|
||
const sequence = ++boundaryLoadSequence;
|
||
const zoom = Math.round(map.getZoom());
|
||
if (zoom < 3) {
|
||
administrativeBoundaryLayer.clearLayers();
|
||
lastAdministrativeBoundaryElements = [];
|
||
if (boundaryStatus) boundaryStatus.textContent = "请放大到 Z3 以上加载行政边界。";
|
||
return;
|
||
}
|
||
const bounds = map.getBounds();
|
||
const params = new URLSearchParams({
|
||
south: bounds.getSouth().toFixed(7),
|
||
west: bounds.getWest().toFixed(7),
|
||
north: bounds.getNorth().toFixed(7),
|
||
east: bounds.getEast().toFixed(7),
|
||
zoom: String(zoom),
|
||
format: "delta-v1"
|
||
});
|
||
if (boundaryStatus) boundaryStatus.textContent = "正在匹配当前视窗的行政边界…";
|
||
try {
|
||
const response = await fetchWithTimeout(
|
||
mapServiceUrl("api/boundaries?" + params.toString()),
|
||
{ headers: { Accept: "application/json" } },
|
||
45000
|
||
);
|
||
const data = await response.json().catch(() => ({}));
|
||
if (!response.ok) throw new Error(data.error || ("HTTP " + response.status));
|
||
if (sequence !== boundaryLoadSequence || !toggle.checked) return;
|
||
const elements = decodeTransferElements(data, "boundary");
|
||
const counts = renderAdministrativeBoundaries(elements);
|
||
const total = counts.high + counts.middle + counts.local;
|
||
if (boundaryStatus) {
|
||
boundaryStatus.textContent = total
|
||
? "已显示行政边界 " + total + " 段(省/国界 " + counts.high +
|
||
" · 地级 " + counts.middle + " · 县级 " + counts.local + ",本地缓存)"
|
||
: "当前视窗没有可用的行政边界,请放大或移动到边界附近重试。";
|
||
}
|
||
} catch (error) {
|
||
if (sequence !== boundaryLoadSequence || !toggle.checked) return;
|
||
if (boundaryStatus) boundaryStatus.textContent = "行政边界加载失败:" + error.message;
|
||
}
|
||
};
|
||
|
||
const loadRailData = async (options = {}) => {
|
||
const enabledLayers = [];
|
||
const nationalOn = document.getElementById("nationalRailToggle").checked;
|
||
const metroOn = document.getElementById("metroToggle").checked;
|
||
if (nationalOn) enabledLayers.push("国铁");
|
||
if (metroOn) enabledLayers.push("地铁");
|
||
|
||
if (!enabledLayers.length) {
|
||
railStatus.textContent = "铁路矢量图层尚未加载。";
|
||
nationalRailStatus.hidden = true;
|
||
metroStatus.hidden = true;
|
||
showToast("请先打开“国铁线路”或“地铁线路”。");
|
||
return;
|
||
}
|
||
|
||
if (map.getZoom() < 3) {
|
||
railLoadSequence += 1;
|
||
nationalRailGroup.clearLayers();
|
||
metroGroup.clearLayers();
|
||
renderedRailFeatureIds = new Set();
|
||
loadedRailElements = [];
|
||
showToast("请放大到 Z3 以上加载铁路数据。");
|
||
railStatus.textContent = "当前缩放级别过低,未请求铁路矢量数据。";
|
||
if (nationalOn) {
|
||
nationalRailStatus.hidden = false;
|
||
nationalRailStatus.textContent = "请放大到 Z3 以上加载国铁线路。";
|
||
}
|
||
if (metroOn) {
|
||
metroStatus.hidden = false;
|
||
metroStatus.textContent = "请放大到 Z3 以上加载地铁线路。";
|
||
}
|
||
return;
|
||
}
|
||
|
||
const sequence = ++railLoadSequence;
|
||
const bounds = map.getBounds().pad(0.03);
|
||
let railTileZoom = Math.min(16, Math.max(3, Math.round(map.getZoom())));
|
||
const railTileCoordinates = (zoom) => {
|
||
const coordinates = [];
|
||
const x0 = lonToVectorTile(bounds.getWest(), zoom);
|
||
const x1 = lonToVectorTile(bounds.getEast(), zoom);
|
||
const y0 = latToVectorTile(bounds.getNorth(), zoom);
|
||
const y1 = latToVectorTile(bounds.getSouth(), zoom);
|
||
for (let y = y0; y <= y1; y += 1) {
|
||
for (let x = x0; x <= x1; x += 1) coordinates.push([x, y]);
|
||
}
|
||
return coordinates;
|
||
};
|
||
let coordinates = railTileCoordinates(railTileZoom);
|
||
while (coordinates.length > 64 && railTileZoom > 3) {
|
||
railTileZoom -= 1;
|
||
coordinates = railTileCoordinates(railTileZoom);
|
||
}
|
||
const state = {
|
||
total: coordinates.length,
|
||
completed: 0,
|
||
failed: 0,
|
||
nationalCount: 0,
|
||
metroCount: 0,
|
||
aggregating: false,
|
||
sources: new Set(),
|
||
cacheStates: new Set()
|
||
};
|
||
nationalRailGroup.clearLayers();
|
||
metroGroup.clearLayers();
|
||
renderedRailFeatureIds = new Set();
|
||
loadedRailElements = [];
|
||
localRailRendered = false;
|
||
localRailViewKey = "";
|
||
nationalOn ? map.addLayer(nationalRailGroup) : map.removeLayer(nationalRailGroup);
|
||
metroOn ? map.addLayer(metroGroup) : map.removeLayer(metroGroup);
|
||
nationalRailStatus.hidden = !nationalOn;
|
||
metroStatus.hidden = !metroOn;
|
||
if (nationalOn) nationalRailStatus.textContent = "正在加载当前视窗…";
|
||
if (metroOn) metroStatus.textContent = "正在加载当前视窗…";
|
||
setStatus("正在加载当前视窗铁路数据…", "busy");
|
||
railStatus.textContent = "正在加载当前视窗铁路…";
|
||
if (!options.quiet) showToast("正在加载当前视窗铁路瓦片。");
|
||
|
||
const requestRailTile = async ([x, y]) => {
|
||
const params = new URLSearchParams({
|
||
dataset: "openfreemap-rail-tiles-v2",
|
||
include: [nationalOn ? "rail" : "", metroOn ? "metro" : ""]
|
||
.filter(Boolean)
|
||
.join(","),
|
||
refresh: options.force ? "1" : "0"
|
||
});
|
||
const response = await fetchWithTimeout(
|
||
mapServiceUrl(
|
||
"api/rail-tiles/" + railTileZoom + "/" + x + "/" + y + ".json?" +
|
||
params.toString()
|
||
),
|
||
{ headers: { Accept: "application/json" } },
|
||
50000
|
||
);
|
||
if (!response.ok) throw new Error("HTTP " + response.status);
|
||
return {
|
||
data: await response.json(),
|
||
cacheState: response.headers.get("X-Cache") || ""
|
||
};
|
||
};
|
||
|
||
const tasks = coordinates.map(async (coordinate) => {
|
||
const result = await requestRailTile(coordinate);
|
||
if (sequence !== railLoadSequence) return;
|
||
const decodedElements = decodeTransferElements(result.data, "rail");
|
||
loadedRailElements.push(...decodedElements);
|
||
const counts = renderRailElements(decodedElements, { replace: false });
|
||
state.completed += 1;
|
||
state.nationalCount += counts.nationalCount;
|
||
state.metroCount += counts.metroCount;
|
||
if (result.data.aggregating) state.aggregating = true;
|
||
if (result.data.source) state.sources.add(result.data.source);
|
||
if (result.cacheState) state.cacheStates.add(result.cacheState);
|
||
if (nationalOn) {
|
||
nationalRailStatus.textContent =
|
||
"正在加载当前视窗:国铁 " + state.nationalCount + " 段";
|
||
}
|
||
if (metroOn) {
|
||
metroStatus.textContent =
|
||
"正在加载当前视窗:地铁 " + state.metroCount + " 段";
|
||
}
|
||
});
|
||
const settled = await Promise.allSettled(tasks);
|
||
if (sequence !== railLoadSequence) return;
|
||
state.failed = settled.filter((item) => item.status === "rejected").length;
|
||
|
||
if (state.completed) {
|
||
const supplemented = ensureLocalRailFallback();
|
||
if (supplemented) {
|
||
state.nationalCount = supplemented.nationalCount;
|
||
state.metroCount = supplemented.metroCount;
|
||
}
|
||
}
|
||
|
||
if (!state.completed) {
|
||
if ((options.retryPass || 0) < 3) {
|
||
window.setTimeout(() => {
|
||
if (sequence === railLoadSequence &&
|
||
(document.getElementById("nationalRailToggle").checked ||
|
||
document.getElementById("metroToggle").checked)) {
|
||
void loadRailData({ retryPass: (options.retryPass || 0) + 1 });
|
||
}
|
||
}, 15000);
|
||
}
|
||
const fallbackCounts = ensureLocalRailFallback();
|
||
if (localRailRendered || fallbackCounts) {
|
||
railStatus.textContent = "地图服务暂不可用,继续显示内置北京及周边铁路数据。";
|
||
if (nationalOn) nationalRailStatus.textContent = "国铁线路暂未取得在线数据,当前显示内置兜底数据。";
|
||
if (metroOn) metroStatus.textContent = "地铁线路暂未取得在线数据,当前显示内置兜底数据。";
|
||
setStatus("地图已就绪");
|
||
} else {
|
||
railStatus.textContent = "无法连接本地地图服务。请先运行 python server.py。";
|
||
if (nationalOn) nationalRailStatus.textContent = "国铁线路加载失败:本地地图服务未连接。";
|
||
if (metroOn) metroStatus.textContent = "地铁线路加载失败:本地地图服务未连接。";
|
||
setStatus("本地地图服务未连接", "error");
|
||
showToast("无法连接本地地图服务,请先运行 python server.py。", "error");
|
||
}
|
||
return;
|
||
}
|
||
const summary = "国铁 " + state.nationalCount + " 段 · 地铁 " + state.metroCount + " 段";
|
||
const sourceLabel = state.sources.has("openfreemap")
|
||
? "OpenFreeMap 全球矢量瓦片(浏览器/本地服务缓存)"
|
||
: "OSM / Overpass(本地服务缓存)";
|
||
const tileLevelSummary =
|
||
" · 铁路瓦片 Z" + railTileZoom +
|
||
(railTileZoom > OPENFREEMAP_SOURCE_MAX_ZOOM
|
||
? "(源 Z" + OPENFREEMAP_SOURCE_MAX_ZOOM + ")"
|
||
: "");
|
||
railStatus.textContent =
|
||
"当前视窗铁路加载完成。数据来自" + sourceLabel + tileLevelSummary +
|
||
(state.cacheStates.size ? "(" + Array.from(state.cacheStates).join(" / ") + ")" : "") + "。";
|
||
if (nationalOn) {
|
||
nationalRailStatus.textContent =
|
||
"已加载当前视窗:国铁 " + state.nationalCount + " 段。来源:" +
|
||
sourceLabel + tileLevelSummary;
|
||
}
|
||
if (metroOn) {
|
||
metroStatus.textContent =
|
||
"已加载当前视窗:地铁 " + state.metroCount + " 段。来源:" +
|
||
sourceLabel + tileLevelSummary;
|
||
}
|
||
if (state.failed && (options.retryPass || 0) < 3) {
|
||
railStatus.textContent += " 部分区域失败,将在 15 秒后自动重试。";
|
||
if (nationalOn) nationalRailStatus.textContent += " 部分区域将自动重试。";
|
||
if (metroOn) metroStatus.textContent += " 部分区域将自动重试。";
|
||
window.setTimeout(() => {
|
||
if (sequence === railLoadSequence &&
|
||
(document.getElementById("nationalRailToggle").checked ||
|
||
document.getElementById("metroToggle").checked)) {
|
||
void loadRailData({ retryPass: (options.retryPass || 0) + 1 });
|
||
}
|
||
}, 15000);
|
||
}
|
||
if (state.aggregating && (options.aggregationPass || 0) < 15) {
|
||
const aggregationNotice = " 低缩放铁路正在后台聚合,完成后会自动刷新;当前响应不等待聚合。";
|
||
railStatus.textContent += aggregationNotice;
|
||
if (nationalOn) nationalRailStatus.textContent += aggregationNotice;
|
||
if (metroOn) metroStatus.textContent += aggregationNotice;
|
||
window.setTimeout(() => {
|
||
if (sequence === railLoadSequence &&
|
||
(document.getElementById("nationalRailToggle").checked ||
|
||
document.getElementById("metroToggle").checked)) {
|
||
void loadRailData({
|
||
aggregationPass: (options.aggregationPass || 0) + 1,
|
||
quiet: true
|
||
});
|
||
}
|
||
}, 4000);
|
||
}
|
||
setStatus("地图已就绪");
|
||
if (!options.quiet) {
|
||
showToast(state.failed ? "铁路部分区域后台重试中:" + summary : "当前视窗铁路加载完成:" + summary);
|
||
}
|
||
};
|
||
const syncRailLayers = (reload) => {
|
||
const nationalOn = document.getElementById("nationalRailToggle").checked;
|
||
const metroOn = document.getElementById("metroToggle").checked;
|
||
|
||
if (!reload) ensureLocalRailFallback();
|
||
nationalOn ? map.addLayer(nationalRailGroup) : map.removeLayer(nationalRailGroup);
|
||
metroOn ? map.addLayer(metroGroup) : map.removeLayer(metroGroup);
|
||
nationalRailStatus.hidden = !nationalOn;
|
||
metroStatus.hidden = !metroOn;
|
||
|
||
if (reload && (nationalOn || metroOn)) loadRailData();
|
||
if (!nationalOn && !metroOn) {
|
||
window.clearTimeout(railPendingPollTimer);
|
||
railStatus.textContent = document.getElementById("railTileToggle").checked
|
||
? "铁路基础设施已显示;国铁、地铁矢量未开启。"
|
||
: "铁路图层均已关闭。";
|
||
}
|
||
updateLegendVisibility();
|
||
};
|
||
|
||
window.addEventListener("mapstudio:optional-data-ready", (event) => {
|
||
if (event.detail?.source !== "vendor/rail-beijing.js?v=20261105-1") return;
|
||
const nationalOn = document.getElementById("nationalRailToggle").checked;
|
||
const metroOn = document.getElementById("metroToggle").checked;
|
||
if (!nationalOn && !metroOn) return;
|
||
const fallbackCounts = ensureLocalRailFallback();
|
||
if (!fallbackCounts) return;
|
||
if (nationalOn) {
|
||
nationalRailStatus.textContent =
|
||
"已加载内置北京及周边备用数据:国铁 " + fallbackCounts.nationalCount + " 段";
|
||
}
|
||
if (metroOn) {
|
||
metroStatus.textContent =
|
||
"已加载内置北京及周边备用数据:地铁 " + fallbackCounts.metroCount + " 段";
|
||
}
|
||
});
|
||
|
||
const renderWaterElements = (elements, options = {}) => {
|
||
const replace = options.replace !== false;
|
||
if (replace) {
|
||
waterLayerGroup.clearLayers();
|
||
renderedWaterFeatureIds = new Set();
|
||
}
|
||
let polygons = 0;
|
||
let lines = 0;
|
||
const samePoint = (a, b) =>
|
||
Math.abs(a[0] - b[0]) < 1e-7 && Math.abs(a[1] - b[1]) < 1e-7;
|
||
const addPolygon = (latlngs) => {
|
||
waterLayerGroup.addLayer(
|
||
L.polygon(latlngs, {
|
||
pane: "waterPane",
|
||
color: themeColors.water,
|
||
stroke: false,
|
||
fillColor: themeColors.water,
|
||
fillOpacity: 0.34,
|
||
interactive: false
|
||
})
|
||
);
|
||
polygons += 1;
|
||
};
|
||
const stitchRings = (segments) => {
|
||
const remaining = segments.filter((segment) => segment.length >= 2);
|
||
const rings = [];
|
||
while (remaining.length) {
|
||
let ring = remaining.shift().slice();
|
||
let merged = true;
|
||
while (merged && !samePoint(ring[0], ring[ring.length - 1])) {
|
||
merged = false;
|
||
for (let index = 0; index < remaining.length; index += 1) {
|
||
const segment = remaining[index];
|
||
if (samePoint(ring[ring.length - 1], segment[0])) {
|
||
ring = ring.concat(segment.slice(1));
|
||
} else if (samePoint(ring[ring.length - 1], segment[segment.length - 1])) {
|
||
ring = ring.concat(segment.slice(0, -1).reverse());
|
||
} else if (samePoint(ring[0], segment[segment.length - 1])) {
|
||
ring = segment.slice(0, -1).concat(ring);
|
||
} else if (samePoint(ring[0], segment[0])) {
|
||
ring = segment.slice(1).reverse().concat(ring);
|
||
} else {
|
||
continue;
|
||
}
|
||
remaining.splice(index, 1);
|
||
merged = true;
|
||
break;
|
||
}
|
||
}
|
||
if (ring.length >= 4 && samePoint(ring[0], ring[ring.length - 1])) {
|
||
rings.push(ring);
|
||
}
|
||
}
|
||
return rings;
|
||
};
|
||
elements.forEach((element) => {
|
||
if (element.id && renderedWaterFeatureIds.has(element.id)) return;
|
||
if (element.id) renderedWaterFeatureIds.add(element.id);
|
||
const geometry = element.geometry || [];
|
||
const tags = element.tags || {};
|
||
if (element.type === "relation" && Array.isArray(element.members)) {
|
||
const outerSegments = element.members
|
||
.filter((member) => member.role !== "inner" && Array.isArray(member.geometry))
|
||
.map((member) => member.geometry.map((point) => [point.lat, point.lon]));
|
||
stitchRings(outerSegments).forEach(addPolygon);
|
||
return;
|
||
}
|
||
if (geometry.length < 2) return;
|
||
const latlngs = geometry.map((point) => [point.lat, point.lon]);
|
||
const waterway = tags.waterway;
|
||
const isLinear = waterway && waterway !== "riverbank";
|
||
if (isLinear) {
|
||
const weight = waterway === "river" ? 3 : waterway === "canal" ? 2.2 : waterway === "drain" ? 1.5 : 1.2;
|
||
waterLayerGroup.addLayer(
|
||
L.polyline(latlngs, {
|
||
pane: "waterPane",
|
||
color: themeColors.water,
|
||
weight,
|
||
opacity: 0.82,
|
||
interactive: false
|
||
})
|
||
);
|
||
lines += 1;
|
||
return;
|
||
}
|
||
const first = geometry[0];
|
||
const last = geometry[geometry.length - 1];
|
||
const closed = first.lat === last.lat && first.lon === last.lon;
|
||
if (closed && (tags.natural === "water" || tags.waterway === "riverbank" || tags.water)) {
|
||
addPolygon(latlngs);
|
||
}
|
||
});
|
||
return { polygons, lines };
|
||
};
|
||
|
||
const renderPortElements = (elements, options = {}) => {
|
||
if (options.replace !== false) {
|
||
portLayerGroup.clearLayers();
|
||
renderedPortFeatureIds = new Set();
|
||
}
|
||
let count = 0;
|
||
(elements || []).forEach((element) => {
|
||
if (element.id && renderedPortFeatureIds.has(element.id)) return;
|
||
const geometry = element.geometry || [];
|
||
if (!geometry.length) return;
|
||
if (element.id) renderedPortFeatureIds.add(element.id);
|
||
const tags = element.tags || {};
|
||
const label = tags.name || tags.port || "港口 / 码头";
|
||
const latlngs = geometry.map((point) => [point.lat, point.lon]);
|
||
if (element.type === "point" || latlngs.length === 1) {
|
||
portLayerGroup.addLayer(
|
||
L.circleMarker(latlngs[0], {
|
||
pane: "portPane",
|
||
radius: 5,
|
||
color: "#ffffff",
|
||
weight: 1.8,
|
||
fillColor: themeColors.port,
|
||
fillOpacity: 0.94
|
||
}).bindPopup(() =>
|
||
"<strong>" + escapeHtml(label) + "</strong><br>港口 / 码头:" +
|
||
escapeHtml(tags.port || "港口") + "<br>" + formatLatLng(latlngs[0])
|
||
)
|
||
);
|
||
} else if (latlngs.length >= 3) {
|
||
const polygon = L.polygon(latlngs, {
|
||
pane: "portPane",
|
||
color: themeColors.port,
|
||
weight: 1.4,
|
||
opacity: 0.78,
|
||
fillColor: themeColors.port,
|
||
fillOpacity: 0.16
|
||
});
|
||
polygon.bindPopup("<strong>" + escapeHtml(label) + "</strong><br>港口 / 码头范围");
|
||
portLayerGroup.addLayer(polygon);
|
||
} else {
|
||
return;
|
||
}
|
||
count += 1;
|
||
});
|
||
return count;
|
||
};
|
||
|
||
const renderVegetationElements = (elements, options = {}) => {
|
||
if (options.replace !== false) {
|
||
vegetationLayerGroup.clearLayers();
|
||
renderedVegetationFeatureIds = new Set();
|
||
}
|
||
let count = 0;
|
||
(elements || []).forEach((element) => {
|
||
if (element.id && renderedVegetationFeatureIds.has(element.id)) return;
|
||
const geometry = element.geometry || [];
|
||
if (geometry.length < 3) return;
|
||
if (element.id) renderedVegetationFeatureIds.add(element.id);
|
||
const tags = element.tags || {};
|
||
const vegetation = tags.vegetation || "vegetation";
|
||
const color = themeColors.vegetation;
|
||
vegetationLayerGroup.addLayer(
|
||
L.polygon(geometry.map((point) => [point.lat, point.lon]), {
|
||
pane: "vegetationPane",
|
||
color,
|
||
stroke: false,
|
||
fillColor: color,
|
||
fillOpacity: vegetation === "wood" || vegetation === "forest" ? 0.25 : 0.18,
|
||
interactive: false
|
||
})
|
||
);
|
||
count += 1;
|
||
});
|
||
return count;
|
||
};
|
||
|
||
const loadWaterData = async (options = {}) => {
|
||
const waterOn = document.getElementById("waterToggle").checked;
|
||
const portsOn = document.getElementById("portToggle").checked;
|
||
const vegetationOn = document.getElementById("vegetationToggle").checked;
|
||
const environmentStatuses = [
|
||
[waterOn, waterStatus],
|
||
[portsOn, portStatus],
|
||
[vegetationOn, vegetationStatus]
|
||
];
|
||
if (!waterOn && !portsOn && !vegetationOn) {
|
||
environmentStatuses.forEach(([, element]) => { element.hidden = true; });
|
||
return;
|
||
}
|
||
if (map.getZoom() < 3) {
|
||
waterLoadSequence += 1;
|
||
waterLayerGroup.clearLayers();
|
||
portLayerGroup.clearLayers();
|
||
vegetationLayerGroup.clearLayers();
|
||
renderedWaterFeatureIds = new Set();
|
||
renderedPortFeatureIds = new Set();
|
||
renderedVegetationFeatureIds = new Set();
|
||
environmentStatuses.forEach(([enabled, element]) => {
|
||
if (!enabled) return;
|
||
element.hidden = false;
|
||
element.textContent = "请放大到 Z3 以上加载当前图层。";
|
||
});
|
||
return;
|
||
}
|
||
const sequence = ++waterLoadSequence;
|
||
const blocks = getViewportBlocks();
|
||
const state = {
|
||
total: blocks.length,
|
||
completed: 0,
|
||
failed: 0,
|
||
polygons: 0,
|
||
lines: 0,
|
||
ports: 0,
|
||
vegetation: 0,
|
||
sources: new Set(),
|
||
cacheStates: new Set(),
|
||
tileZooms: new Set(),
|
||
sourceTileZooms: new Set()
|
||
};
|
||
waterLayerGroup.clearLayers();
|
||
portLayerGroup.clearLayers();
|
||
vegetationLayerGroup.clearLayers();
|
||
renderedWaterFeatureIds = new Set();
|
||
renderedPortFeatureIds = new Set();
|
||
renderedVegetationFeatureIds = new Set();
|
||
loadedWaterElements = [];
|
||
loadedPortElements = [];
|
||
loadedVegetationElements = [];
|
||
if (waterOn) map.addLayer(waterLayerGroup);
|
||
if (portsOn) map.addLayer(portLayerGroup);
|
||
if (vegetationOn) map.addLayer(vegetationLayerGroup);
|
||
environmentStatuses.forEach(([enabled, element]) => {
|
||
if (!enabled) return;
|
||
element.hidden = false;
|
||
element.textContent = "正在加载当前视窗…";
|
||
});
|
||
setStatus("正在加载当前视窗环境图层…", "busy");
|
||
showToast("正在加载当前区域水域、港口和植被;外地首次使用需完成后台分块下载。");
|
||
|
||
const requestWaterBlock = async (block, allowPending) => {
|
||
const params = new URLSearchParams({
|
||
south: String(block.getSouth()),
|
||
west: String(block.getWest()),
|
||
north: String(block.getNorth()),
|
||
east: String(block.getEast()),
|
||
zoom: String(map.getZoom()),
|
||
dataset: "openfreemap-environment-block-v6",
|
||
include: [
|
||
waterOn ? "water" : "",
|
||
portsOn ? "ports" : "",
|
||
vegetationOn ? "vegetation" : ""
|
||
].filter(Boolean).join(","),
|
||
format: "delta-v1",
|
||
refresh: options.force ? "1" : "0"
|
||
});
|
||
const response = await fetchWithTimeout(
|
||
mapServiceUrl("api/water?" + params.toString()),
|
||
{ headers: { Accept: "application/json" } },
|
||
50000
|
||
);
|
||
if (response.status === 202 && allowPending) {
|
||
const pending = await response.json();
|
||
const ready = await waitForDataJob(
|
||
"water",
|
||
pending.cacheKey,
|
||
() => sequence === waterLoadSequence
|
||
);
|
||
if (!ready) throw new Error("Water block timed out");
|
||
return requestWaterBlock(block, false);
|
||
}
|
||
if (!response.ok) throw new Error("HTTP " + response.status);
|
||
return {
|
||
data: await response.json(),
|
||
cacheState: response.headers.get("X-Cache") || ""
|
||
};
|
||
};
|
||
|
||
let nextBlockIndex = 0;
|
||
const workerCount = Math.min(5, blocks.length);
|
||
const workers = Array.from({ length: workerCount }, async () => {
|
||
while (nextBlockIndex < blocks.length) {
|
||
const block = blocks[nextBlockIndex];
|
||
nextBlockIndex += 1;
|
||
try {
|
||
const result = await requestWaterBlock(block, true);
|
||
if (sequence !== waterLoadSequence) return;
|
||
const decodedWater = waterOn ? decodeTransferElements(result.data, "water") : [];
|
||
const decodedPorts = portsOn ? decodeTransferElements(result.data, "port", "ports") : [];
|
||
const decodedVegetation = vegetationOn
|
||
? decodeTransferElements(result.data, "vegetation", "vegetation")
|
||
: [];
|
||
if (waterOn) loadedWaterElements.push(...decodedWater);
|
||
if (portsOn) loadedPortElements.push(...decodedPorts);
|
||
if (vegetationOn) loadedVegetationElements.push(...decodedVegetation);
|
||
const waterCounts = waterOn
|
||
? renderWaterElements(decodedWater, { replace: false })
|
||
: { polygons: 0, lines: 0 };
|
||
const portCount = portsOn
|
||
? renderPortElements(decodedPorts, { replace: false })
|
||
: 0;
|
||
const vegetationCount = vegetationOn
|
||
? renderVegetationElements(decodedVegetation, { replace: false })
|
||
: 0;
|
||
state.completed += 1;
|
||
state.polygons += waterCounts.polygons;
|
||
state.lines += waterCounts.lines;
|
||
state.ports += portCount;
|
||
state.vegetation += vegetationCount;
|
||
if (result.data.source) state.sources.add(result.data.source);
|
||
if (result.cacheState) state.cacheStates.add(result.cacheState);
|
||
if (result.data.tileZoom) state.tileZooms.add(Number(result.data.tileZoom));
|
||
if (result.data.sourceTileZoom) {
|
||
state.sourceTileZooms.add(Number(result.data.sourceTileZoom));
|
||
}
|
||
if (waterOn) {
|
||
waterStatus.textContent =
|
||
"正在加载当前视窗:面状水域 " + state.polygons +
|
||
" · 河流线 " + state.lines;
|
||
}
|
||
if (portsOn) {
|
||
portStatus.textContent = "正在加载当前视窗:港口 " + state.ports;
|
||
}
|
||
if (vegetationOn) {
|
||
vegetationStatus.textContent =
|
||
"正在加载当前视窗:植被 " + state.vegetation;
|
||
}
|
||
} catch (error) {
|
||
state.failed += 1;
|
||
}
|
||
}
|
||
});
|
||
await Promise.all(workers);
|
||
if (sequence !== waterLoadSequence) return;
|
||
if (!state.completed) {
|
||
if ((options.retryPass || 0) < 3) {
|
||
window.setTimeout(() => {
|
||
if (sequence === waterLoadSequence &&
|
||
(document.getElementById("waterToggle").checked ||
|
||
document.getElementById("portToggle").checked ||
|
||
document.getElementById("vegetationToggle").checked)) {
|
||
void loadWaterData({ retryPass: (options.retryPass || 0) + 1 });
|
||
}
|
||
}, 15000);
|
||
}
|
||
environmentStatuses.forEach(([enabled, element]) => {
|
||
if (enabled) {
|
||
element.textContent = "当前视窗暂未返回,后台仍在重试;完成后会自动显示。";
|
||
}
|
||
});
|
||
setStatus("水域数据暂时不可用", "error");
|
||
return;
|
||
}
|
||
const sourceLabel = state.sources.has("openfreemap")
|
||
? "OpenFreeMap 全球矢量瓦片"
|
||
: "OSM / Overpass";
|
||
const requestedZooms = Array.from(state.tileZooms).filter(Number.isFinite);
|
||
const sourceZooms = Array.from(state.sourceTileZooms).filter(Number.isFinite);
|
||
const zoomSummary = requestedZooms.length
|
||
? " · 数据级 Z" + Math.min(...requestedZooms) +
|
||
(Math.max(...requestedZooms) !== Math.min(...requestedZooms)
|
||
? "–Z" + Math.max(...requestedZooms)
|
||
: "") +
|
||
(sourceZooms.length
|
||
? "(源 Z" + Math.min(...sourceZooms) +
|
||
(Math.max(...sourceZooms) !== Math.min(...sourceZooms)
|
||
? "–Z" + Math.max(...sourceZooms)
|
||
: "") + ")"
|
||
: "")
|
||
: "";
|
||
const metadataSuffix =
|
||
"。来源:" + sourceLabel + zoomSummary +
|
||
(state.cacheStates.size ? "(" + Array.from(state.cacheStates).join(" / ") + ")" : "");
|
||
if (waterOn) {
|
||
waterStatus.textContent =
|
||
"已加载当前视窗:面状水域 " + state.polygons +
|
||
" · 河流线 " + state.lines + metadataSuffix;
|
||
}
|
||
if (portsOn) {
|
||
portStatus.textContent =
|
||
"已加载当前视窗:港口 " + state.ports + metadataSuffix;
|
||
}
|
||
if (vegetationOn) {
|
||
vegetationStatus.textContent =
|
||
"已加载当前视窗:植被 " + state.vegetation + metadataSuffix;
|
||
}
|
||
if (state.failed && (options.retryPass || 0) < 3) {
|
||
environmentStatuses.forEach(([enabled, element]) => {
|
||
if (enabled) element.textContent += " 部分区域失败,将在 15 秒后自动重试。";
|
||
});
|
||
window.setTimeout(() => {
|
||
if (sequence === waterLoadSequence &&
|
||
(document.getElementById("waterToggle").checked ||
|
||
document.getElementById("portToggle").checked ||
|
||
document.getElementById("vegetationToggle").checked)) {
|
||
void loadWaterData({ retryPass: (options.retryPass || 0) + 1 });
|
||
}
|
||
}, 15000);
|
||
}
|
||
setStatus("地图已就绪");
|
||
};
|
||
|
||
const checkMapService = async (notify = true) => {
|
||
try {
|
||
const response = await fetchWithTimeout(
|
||
mapServiceUrl("api/status"),
|
||
{ headers: { Accept: "application/json" } },
|
||
5000
|
||
);
|
||
if (!response.ok) throw new Error("HTTP " + response.status);
|
||
const status = await response.json();
|
||
const cacheOnly = Boolean(status.cacheOnly);
|
||
if (notify) {
|
||
showToast(
|
||
cacheOnly
|
||
? "服务器处于仅缓存模式:缺失瓦片将显示占位图。"
|
||
: "本地地图服务已连接:缓存 " + status.cacheFiles + " 个文件。"
|
||
);
|
||
}
|
||
return status;
|
||
} catch (error) {
|
||
setStatus("本地地图服务未连接", "error");
|
||
if (notify) {
|
||
showToast("无法连接本地地图服务,请先运行:python server.py", "error");
|
||
}
|
||
return null;
|
||
}
|
||
};
|
||
|
||
const applyContourControls = () => {
|
||
const intervalValue = document.getElementById("contourInterval").value;
|
||
contourConfig.interval = intervalValue === "auto" ? 0 : Number(intervalValue);
|
||
contourConfig.startElevation = Number(document.getElementById("contourStart").value) || 0;
|
||
contourConfig.boldEvery = Number(document.getElementById("contourBoldEvery").value);
|
||
contourConfig.color = document.getElementById("contourColor").value;
|
||
contourConfig.width = Number(document.getElementById("contourWidth").value);
|
||
contourConfig.boldWidth = Number(document.getElementById("contourBoldWidth").value);
|
||
document.getElementById("contourWidthValue").textContent = contourConfig.width.toFixed(1) + " px";
|
||
document.getElementById("contourBoldWidthValue").textContent = contourConfig.boldWidth.toFixed(1) + " px";
|
||
if (map.hasLayer(contourTerrainLayer)) contourTerrainLayer.redraw();
|
||
updateLegendVisibility();
|
||
scheduleWorkspaceSave();
|
||
};
|
||
|
||
const setContourOptionsVisibility = (visible) => {
|
||
const options = document.getElementById("contourOptions");
|
||
options.hidden = !visible;
|
||
if (!visible) options.open = false;
|
||
document.getElementById("contourControls").classList.toggle("is-disabled", !visible);
|
||
};
|
||
|
||
const applyGridControls = () => {
|
||
const intervalInput = document.getElementById("gridInterval");
|
||
const intervalValue = intervalInput.value.trim();
|
||
const projected = selectedCoordinateSystem === "webmercator";
|
||
const intervalUnit = projected ? "meter" : document.getElementById("gridIntervalUnit").value;
|
||
const unitFactor = intervalUnit === "minute" ? 1 / 60 : intervalUnit === "second" ? 1 / 3600 : 1;
|
||
const parsedInterval = Number(intervalValue);
|
||
gridConfig.interval = intervalValue && Number.isFinite(parsedInterval) && parsedInterval > 0
|
||
? parsedInterval * unitFactor
|
||
: 0;
|
||
gridConfig.startLon = Number(document.getElementById("gridStartLon").value) || 0;
|
||
gridConfig.startLat = Number(document.getElementById("gridStartLat").value) || 0;
|
||
gridConfig.color = document.getElementById("gridColor").value;
|
||
gridConfig.width = Number(document.getElementById("gridWidth").value);
|
||
document.getElementById("gridWidthValue").textContent = gridConfig.width.toFixed(1) + " px";
|
||
const unitSymbol = intervalUnit === "meter" ? "m" : intervalUnit === "minute" ? "′" : intervalUnit === "second" ? "″" : "°";
|
||
document.getElementById("gridIntervalEquivalent").textContent = gridConfig.interval
|
||
? (intervalUnit === "degree" || intervalUnit === "meter"
|
||
? intervalValue + (intervalUnit === "meter" ? " m" : "°")
|
||
: intervalValue + unitSymbol + " = " + gridConfig.interval.toFixed(6).replace(/0+$/, "").replace(/\.$/, "") + "°")
|
||
: "自动";
|
||
gridLayer.redraw();
|
||
updateLegendVisibility();
|
||
scheduleWorkspaceSave();
|
||
};
|
||
|
||
|
||
renderDrawingList();
|
||
|
||
function formatScaleDistance(meters) {
|
||
if (meters >= 1000) return (meters / 1000).toFixed(meters >= 10000 ? 0 : 1) + " km";
|
||
return Math.round(meters) + " m";
|
||
}
|
||
|
||
function niceScaleDistance(meters) {
|
||
if (!Number.isFinite(meters) || meters <= 0) return 100;
|
||
const power = Math.pow(10, Math.floor(Math.log10(meters)));
|
||
const normalized = meters / power;
|
||
const nice = normalized >= 5 ? 10 : normalized >= 2 ? 5 : normalized >= 1 ? 2 : 1;
|
||
return nice * power;
|
||
}
|
||
|
||
const PRINT_PAGE_WIDTH_PX = 297 * 96 / 25.4;
|
||
const PRINT_PAGE_HEIGHT_PX = 210 * 96 / 25.4;
|
||
const getMapLayoutSize = () => ({
|
||
width: map.getContainer().clientWidth || map.getSize().x,
|
||
height: map.getContainer().clientHeight || map.getSize().y
|
||
});
|
||
const updatePrintPreviewScale = () => {
|
||
const scale = Math.min(
|
||
window.innerWidth / PRINT_PAGE_WIDTH_PX,
|
||
window.innerHeight / PRINT_PAGE_HEIGHT_PX
|
||
);
|
||
document.documentElement.style.setProperty("--print-preview-scale", Math.max(0.1, scale).toFixed(4));
|
||
};
|
||
|
||
const printFrame = document.getElementById("printFrame");
|
||
const frameState = { x: 48, y: 48, w: 800, h: 600 };
|
||
let hasRestoredPrintFrame = false;
|
||
const PRINT_LEGEND_RESERVE = 190;
|
||
|
||
function applyFrameState() {
|
||
const layout = getMapLayoutSize();
|
||
const printMode = document.body.classList.contains("print-mode");
|
||
const rightReserve = printMode ? PRINT_LEGEND_RESERVE : 12;
|
||
const topReserve = printMode ? 56 : 12;
|
||
frameState.x = Math.max(12, Math.min(layout.width - 160 - rightReserve, frameState.x));
|
||
frameState.y = Math.max(topReserve, Math.min(layout.height - 120 - 14, frameState.y));
|
||
frameState.w = Math.max(160, Math.min(layout.width - frameState.x - rightReserve, frameState.w));
|
||
frameState.h = Math.max(120, Math.min(layout.height - frameState.y - 14, frameState.h));
|
||
if (!printFrame) return;
|
||
printFrame.style.left = frameState.x + "px";
|
||
printFrame.style.top = frameState.y + "px";
|
||
printFrame.style.width = frameState.w + "px";
|
||
printFrame.style.height = frameState.h + "px";
|
||
const mapElement = map.getContainer();
|
||
if (printMode) {
|
||
const right = Math.max(0, layout.width - frameState.x - frameState.w);
|
||
const bottom = Math.max(0, layout.height - frameState.y - frameState.h);
|
||
const clip = "inset(" + frameState.y + "px " + right + "px " + bottom + "px " + frameState.x + "px)";
|
||
mapElement.style.clipPath = clip;
|
||
mapElement.style.webkitClipPath = clip;
|
||
} else {
|
||
mapElement.style.clipPath = "";
|
||
mapElement.style.webkitClipPath = "";
|
||
}
|
||
}
|
||
|
||
function resetFrameState() {
|
||
const layout = getMapLayoutSize();
|
||
if (document.body.classList.contains("print-mode")) {
|
||
frameState.x = Math.max(32, Math.round(layout.width * 0.035));
|
||
frameState.y = 62;
|
||
frameState.w = Math.max(240, layout.width - frameState.x - PRINT_LEGEND_RESERVE - 18);
|
||
frameState.h = Math.max(180, layout.height - frameState.y - 38);
|
||
} else {
|
||
frameState.x = Math.max(24, Math.round(layout.width * 0.06));
|
||
frameState.y = Math.max(24, Math.round(layout.height * 0.06));
|
||
frameState.w = Math.max(240, layout.width - frameState.x * 2);
|
||
frameState.h = Math.max(180, layout.height - frameState.y * 2);
|
||
}
|
||
applyFrameState();
|
||
}
|
||
|
||
function updatePrintDecor() {
|
||
const bar = document.querySelector(".print-scale-bar");
|
||
const label = document.getElementById("printScaleLabel");
|
||
const titleMeta = document.getElementById("printTitleMeta");
|
||
if (!bar || !label || !titleMeta) return;
|
||
|
||
applyFrameState();
|
||
const nw = map.containerPointToLatLng([frameState.x, frameState.y]);
|
||
const se = map.containerPointToLatLng([frameState.x + frameState.w, frameState.y + frameState.h]);
|
||
const start = map.containerPointToLatLng([0, 0]);
|
||
const end = map.containerPointToLatLng([140, 0]);
|
||
const referenceDistance = haversineDistance(start, end);
|
||
const niceDistance = niceScaleDistance(referenceDistance);
|
||
const width = Math.max(45, Math.min(140, 140 * niceDistance / referenceDistance));
|
||
bar.style.width = width + "px";
|
||
const stripeWidth = width / 4;
|
||
printFrame.style.setProperty("--print-stripe", stripeWidth.toFixed(2) + "px");
|
||
printFrame.style.setProperty("--print-stripe-end", (stripeWidth * 2).toFixed(2) + "px");
|
||
label.textContent = "比例尺 " + formatScaleDistance(niceDistance);
|
||
const printCoordinateSystem = coordinateSystems
|
||
? coordinateSystems.getSystem(selectedCoordinateSystem)
|
||
: { label: "WGS84" };
|
||
const formatPrintCoordinate = (latlng) => coordinateSystems
|
||
? coordinateSystems.formatCompact(latlng.lat, latlng.lng, selectedCoordinateSystem, {
|
||
precision: 4
|
||
})
|
||
: latlng.lat.toFixed(4) + "°, " + latlng.lng.toFixed(4) + "°";
|
||
titleMeta.textContent =
|
||
printCoordinateSystem.label + " · NW " + formatPrintCoordinate(nw) + " · " +
|
||
"SE " + formatPrintCoordinate(se) + " · Z" + map.getZoom();
|
||
updateLegendVisibility();
|
||
}
|
||
|
||
function setPrintMode(active) {
|
||
if (active) updatePrintPreviewScale();
|
||
document.body.classList.toggle("print-mode", active);
|
||
if (active) {
|
||
map.invalidateSize({ animate: false, pan: false });
|
||
if (hasRestoredPrintFrame) applyFrameState();
|
||
else resetFrameState();
|
||
hasRestoredPrintFrame = false;
|
||
updatePrintDecor();
|
||
window.setTimeout(() => {
|
||
map.invalidateSize({ animate: false, pan: false });
|
||
updatePrintDecor();
|
||
}, 80);
|
||
} else {
|
||
const mapElement = map.getContainer();
|
||
mapElement.style.clipPath = "";
|
||
mapElement.style.webkitClipPath = "";
|
||
window.requestAnimationFrame(() => {
|
||
map.invalidateSize({ animate: false, pan: false });
|
||
updatePrintDecor();
|
||
});
|
||
}
|
||
showToast(active ? "已进入制图模式:拖动或调整四角即可设定出图范围。" : "已退出制图模式。");
|
||
}
|
||
|
||
document.getElementById("printModeButton").addEventListener("click", () => {
|
||
setPrintMode(!document.body.classList.contains("print-mode"));
|
||
});
|
||
document.getElementById("exitPrintButton").addEventListener("click", () => setPrintMode(false));
|
||
document.getElementById("exportPrintButton").addEventListener("click", () => {
|
||
if (!document.body.classList.contains("print-mode")) setPrintMode(true);
|
||
window.requestAnimationFrame(() => {
|
||
window.requestAnimationFrame(() => {
|
||
map.invalidateSize({ animate: false, pan: false });
|
||
updatePrintDecor();
|
||
window.print();
|
||
});
|
||
});
|
||
});
|
||
window.addEventListener("beforeprint", () => {
|
||
map.invalidateSize({ animate: false, pan: false });
|
||
updatePrintDecor();
|
||
});
|
||
|
||
if (printFrame) {
|
||
let dragMode = null;
|
||
let dragStart = null;
|
||
let dragInitial = null;
|
||
|
||
const beginDrag = (event, mode) => {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
dragMode = mode;
|
||
dragStart = { x: event.clientX, y: event.clientY };
|
||
dragInitial = { ...frameState };
|
||
window.addEventListener("pointermove", onDragMove);
|
||
window.addEventListener("pointerup", onDragEnd, { once: true });
|
||
};
|
||
|
||
const onDragMove = (event) => {
|
||
if (!dragMode) return;
|
||
const container = map.getContainer();
|
||
const visualScale = container.clientWidth
|
||
? container.getBoundingClientRect().width / container.clientWidth
|
||
: 1;
|
||
const dx = (event.clientX - dragStart.x) / visualScale;
|
||
const dy = (event.clientY - dragStart.y) / visualScale;
|
||
if (dragMode === "move") {
|
||
frameState.x = dragInitial.x + dx;
|
||
frameState.y = dragInitial.y + dy;
|
||
} else {
|
||
if (dragMode.includes("w")) {
|
||
frameState.x = dragInitial.x + dx;
|
||
frameState.w = dragInitial.w - dx;
|
||
}
|
||
if (dragMode.includes("e")) frameState.w = dragInitial.w + dx;
|
||
if (dragMode.includes("n")) {
|
||
frameState.y = dragInitial.y + dy;
|
||
frameState.h = dragInitial.h - dy;
|
||
}
|
||
if (dragMode.includes("s")) frameState.h = dragInitial.h + dy;
|
||
}
|
||
applyFrameState();
|
||
updatePrintDecor();
|
||
};
|
||
|
||
const onDragEnd = () => {
|
||
dragMode = null;
|
||
window.removeEventListener("pointermove", onDragMove);
|
||
scheduleWorkspaceSave();
|
||
};
|
||
|
||
printFrame.addEventListener("pointerdown", (event) => {
|
||
if (event.target.closest("button, input, select, textarea")) return;
|
||
const handle = event.target.closest(".frame-handle");
|
||
beginDrag(event, handle ? handle.dataset.handle : "move");
|
||
});
|
||
}
|
||
|
||
const WORKSPACE_STORAGE_KEY = "mapStudio.workspace.v1";
|
||
let workspaceSaveTimer = null;
|
||
let isRestoringWorkspace = true;
|
||
|
||
const appShell = document.querySelector(".app-shell");
|
||
const layerSidebar = document.getElementById("sidebar");
|
||
const sidebarToggleButton = document.getElementById("toggleSidebar");
|
||
const compactSidebarMedia = window.matchMedia("(max-width: 900px)");
|
||
|
||
const sidebarIsVisible = () => compactSidebarMedia.matches
|
||
? layerSidebar.classList.contains("open")
|
||
: !appShell.classList.contains("sidebar-collapsed");
|
||
|
||
const refreshSidebarToggleState = () => {
|
||
const visible = sidebarIsVisible();
|
||
sidebarToggleButton.setAttribute("aria-expanded", String(visible));
|
||
sidebarToggleButton.setAttribute(
|
||
"aria-label",
|
||
visible ? "隐藏图层面板" : "显示图层面板"
|
||
);
|
||
sidebarToggleButton.title = visible ? "隐藏图层面板" : "显示图层面板";
|
||
};
|
||
|
||
const setSidebarCollapsed = (collapsed, options = {}) => {
|
||
appShell.classList.toggle("sidebar-collapsed", collapsed);
|
||
if (collapsed) layerSidebar.classList.remove("open");
|
||
refreshSidebarToggleState();
|
||
window.requestAnimationFrame(() => map.invalidateSize({ animate: false, pan: false }));
|
||
if (options.persist !== false) scheduleWorkspaceSave();
|
||
};
|
||
|
||
const captureWorkspaceState = () => ({
|
||
version: 1,
|
||
savedAt: new Date().toISOString(),
|
||
layout: {
|
||
sidebarCollapsed: appShell.classList.contains("sidebar-collapsed")
|
||
},
|
||
map: {
|
||
center: [map.getCenter().lat, map.getCenter().lng],
|
||
zoom: map.getZoom(),
|
||
bounds: [
|
||
map.getBounds().getSouth(),
|
||
map.getBounds().getWest(),
|
||
map.getBounds().getNorth(),
|
||
map.getBounds().getEast()
|
||
]
|
||
},
|
||
base: currentBaseKey,
|
||
coordinateSystem: selectedCoordinateSystem,
|
||
coordinateReadoutFormat,
|
||
toggles: {
|
||
grid: document.getElementById("gridToggle").checked,
|
||
contour: document.getElementById("contourToggle").checked,
|
||
hillshade: document.getElementById("hillshadeToggle").checked,
|
||
terrain: document.getElementById("terrainFeatureToggle").checked,
|
||
terrainPeak: document.getElementById("terrainPeakToggle").checked,
|
||
terrainValley: document.getElementById("terrainValleyToggle").checked,
|
||
localVector: document.getElementById("localVectorToggle").checked,
|
||
water: document.getElementById("waterToggle").checked,
|
||
port: document.getElementById("portToggle").checked,
|
||
vegetation: document.getElementById("vegetationToggle").checked,
|
||
railTile: document.getElementById("railTileToggle").checked,
|
||
nationalRail: document.getElementById("nationalRailToggle").checked,
|
||
metro: document.getElementById("metroToggle").checked,
|
||
nationalRailCategories: Object.fromEntries(
|
||
railCategoryKeys.map((key) => [
|
||
key,
|
||
document.getElementById(nationalRailCategoryToggleIds[key]).checked
|
||
])
|
||
),
|
||
metroRailCategories: Object.fromEntries(
|
||
railCategoryKeys.map((key) => [
|
||
key,
|
||
document.getElementById(metroRailCategoryToggleIds[key]).checked
|
||
])
|
||
),
|
||
tdtVectorLabel: document.getElementById("tdtVectorLabelToggle").checked,
|
||
tdtTerrainLabel: document.getElementById("tdtTerrainLabelToggle").checked,
|
||
tdtImageryLabel: document.getElementById("tdtImageryLabelToggle").checked,
|
||
tdtBoundary: document.getElementById("tdtBoundaryToggle").checked
|
||
},
|
||
settings: {
|
||
coordinateSystem: selectedCoordinateSystem,
|
||
coordinateReadoutFormat,
|
||
grid: {
|
||
interval: document.getElementById("gridInterval").value,
|
||
unit: document.getElementById("gridIntervalUnit").value,
|
||
startLon: document.getElementById("gridStartLon").value,
|
||
startLat: document.getElementById("gridStartLat").value,
|
||
color: document.getElementById("gridColor").value,
|
||
width: document.getElementById("gridWidth").value
|
||
},
|
||
contour: {
|
||
interval: document.getElementById("contourInterval").value,
|
||
start: document.getElementById("contourStart").value,
|
||
boldEvery: document.getElementById("contourBoldEvery").value,
|
||
color: document.getElementById("contourColor").value,
|
||
width: document.getElementById("contourWidth").value,
|
||
boldWidth: document.getElementById("contourBoldWidth").value
|
||
},
|
||
boundary: {
|
||
highColor: document.getElementById("boundaryHighColor").value,
|
||
middleColor: document.getElementById("boundaryMiddleColor").value,
|
||
localColor: document.getElementById("boundaryLocalColor").value
|
||
},
|
||
colors: Object.fromEntries(
|
||
Object.entries(themeColorInputs).map(([key, id]) => [
|
||
key,
|
||
document.getElementById(id).value
|
||
])
|
||
),
|
||
railwayLineStyle: document.getElementById("railwayLineStyleSelect").value,
|
||
metroLineStyle: document.getElementById("metroLineStyleSelect").value,
|
||
terrain: {
|
||
threshold: document.getElementById("terrainProminenceThreshold").value
|
||
},
|
||
localVector: {
|
||
groups: Array.from(localVectorSelectedGroups())
|
||
},
|
||
viewshed: {
|
||
height: document.getElementById("viewshedHeight").value,
|
||
innerRadius: document.getElementById("visibilityInnerRadius").value,
|
||
outerRadius: document.getElementById("visibilityOuterRadius").value,
|
||
nearColor: document.getElementById("visibilityNearColor").value,
|
||
midColor: document.getElementById("visibilityMidColor").value,
|
||
farColor: document.getElementById("visibilityFarColor").value
|
||
}
|
||
},
|
||
print: {
|
||
title: document.getElementById("printTitleInput").value,
|
||
frame: { ...frameState }
|
||
}
|
||
});
|
||
|
||
const saveWorkspaceNow = () => {
|
||
if (isRestoringWorkspace || isImportingProject) return;
|
||
window.clearTimeout(workspaceSaveTimer);
|
||
workspaceSaveTimer = null;
|
||
try {
|
||
window.localStorage.setItem(WORKSPACE_STORAGE_KEY, JSON.stringify(captureWorkspaceState()));
|
||
} catch (error) {
|
||
// The map remains usable when browser storage is unavailable.
|
||
}
|
||
};
|
||
|
||
const scheduleWorkspaceSave = () => {
|
||
if (isRestoringWorkspace || isImportingProject) return;
|
||
window.clearTimeout(workspaceSaveTimer);
|
||
workspaceSaveTimer = window.setTimeout(saveWorkspaceNow, 150);
|
||
};
|
||
|
||
const PROJECT_FILE_FORMAT = "MapStudioProject";
|
||
const PROJECT_FILE_VERSION = 1;
|
||
const PROJECT_IMPORT_NOTICE_KEY = "mapStudio.projectImportNotice";
|
||
|
||
const exportProjectFile = () => {
|
||
const now = new Date();
|
||
const payload = {
|
||
format: PROJECT_FILE_FORMAT,
|
||
formatVersion: PROJECT_FILE_VERSION,
|
||
application: "Map Studio",
|
||
exportedAt: now.toISOString(),
|
||
workspace: captureWorkspaceState(),
|
||
drawings: captureDrawingsState()
|
||
};
|
||
const blob = new Blob([JSON.stringify(payload, null, 2)], {
|
||
type: "application/vnd.mapstudio.project+json"
|
||
});
|
||
const href = URL.createObjectURL(blob);
|
||
const stamp = [
|
||
now.getFullYear(),
|
||
String(now.getMonth() + 1).padStart(2, "0"),
|
||
String(now.getDate()).padStart(2, "0"),
|
||
"-",
|
||
String(now.getHours()).padStart(2, "0"),
|
||
String(now.getMinutes()).padStart(2, "0")
|
||
].join("");
|
||
const anchor = document.createElement("a");
|
||
anchor.href = href;
|
||
anchor.download = "MapStudio-" + stamp + ".mpstd";
|
||
document.body.appendChild(anchor);
|
||
anchor.click();
|
||
anchor.remove();
|
||
window.setTimeout(() => URL.revokeObjectURL(href), 1000);
|
||
showToast("工程文件已导出。");
|
||
};
|
||
|
||
const importProjectFile = async (file) => {
|
||
if (!file) return;
|
||
if (file.size > 100 * 1024 * 1024) {
|
||
throw new Error("工程文件超过 100 MB,已拒绝导入。");
|
||
}
|
||
let project;
|
||
try {
|
||
project = JSON.parse(await file.text());
|
||
} catch (error) {
|
||
throw new Error("工程文件不是有效的 JSON。");
|
||
}
|
||
if (
|
||
!project ||
|
||
project.format !== PROJECT_FILE_FORMAT ||
|
||
Number(project.formatVersion) !== PROJECT_FILE_VERSION
|
||
) {
|
||
throw new Error("不是受支持的 MapStudio 工程文件。");
|
||
}
|
||
if (
|
||
!project.workspace ||
|
||
Number(project.workspace.version) !== 1 ||
|
||
!project.drawings ||
|
||
Number(project.drawings.version) !== 1 ||
|
||
!Array.isArray(project.drawings.items)
|
||
) {
|
||
throw new Error("工程数据结构不完整或版本不兼容。");
|
||
}
|
||
const now = new Date().toISOString();
|
||
const workspace = { ...project.workspace, version: 1, savedAt: now };
|
||
const drawings = {
|
||
...project.drawings,
|
||
version: 1,
|
||
savedAt: now,
|
||
items: project.drawings.items
|
||
};
|
||
const serializedWorkspace = JSON.stringify(workspace);
|
||
const serializedDrawings = JSON.stringify(drawings);
|
||
|
||
// Stop every pending save before replacing storage. Reloading the page also
|
||
// fires pagehide/visibilitychange, which would otherwise write old state back.
|
||
window.clearTimeout(workspaceSaveTimer);
|
||
workspaceSaveTimer = null;
|
||
window.clearTimeout(drawingSaveTimer);
|
||
drawingSaveTimer = null;
|
||
drawingGeneration += 1;
|
||
visibilityTask += 1;
|
||
isImportingProject = true;
|
||
|
||
let previousWorkspace = null;
|
||
let previousDrawings = null;
|
||
try {
|
||
previousWorkspace = localStorage.getItem(WORKSPACE_STORAGE_KEY);
|
||
previousDrawings = localStorage.getItem(DRAWING_STORAGE_KEY);
|
||
localStorage.setItem(WORKSPACE_STORAGE_KEY, serializedWorkspace);
|
||
localStorage.setItem(DRAWING_STORAGE_KEY, serializedDrawings);
|
||
if (
|
||
localStorage.getItem(WORKSPACE_STORAGE_KEY) !== serializedWorkspace ||
|
||
localStorage.getItem(DRAWING_STORAGE_KEY) !== serializedDrawings
|
||
) {
|
||
throw new Error("Imported project storage verification failed");
|
||
}
|
||
} catch (error) {
|
||
try {
|
||
if (previousWorkspace === null) localStorage.removeItem(WORKSPACE_STORAGE_KEY);
|
||
else localStorage.setItem(WORKSPACE_STORAGE_KEY, previousWorkspace);
|
||
if (previousDrawings === null) localStorage.removeItem(DRAWING_STORAGE_KEY);
|
||
else localStorage.setItem(DRAWING_STORAGE_KEY, previousDrawings);
|
||
} catch (restoreError) {
|
||
// Preserve the original error; storage is already unavailable.
|
||
}
|
||
isImportingProject = false;
|
||
throw new Error("浏览器存储空间不足或写入校验失败,无法保存工程文件。");
|
||
}
|
||
try {
|
||
sessionStorage.setItem(
|
||
PROJECT_IMPORT_NOTICE_KEY,
|
||
"工程已导入:恢复视图、设置和 " + drawings.items.length + " 项绘制内容。"
|
||
);
|
||
} catch (error) {
|
||
// The project is already saved; only the post-reload notice is unavailable.
|
||
}
|
||
window.setTimeout(() => window.location.reload(), 250);
|
||
};
|
||
|
||
const setInputValue = (id, value) => {
|
||
if (value === undefined || value === null) return;
|
||
document.getElementById(id).value = String(value);
|
||
};
|
||
|
||
const setChecked = (id, value) => {
|
||
if (typeof value === "boolean") document.getElementById(id).checked = value;
|
||
};
|
||
|
||
const restoreWorkspaceState = () => {
|
||
let state = null;
|
||
try {
|
||
state = JSON.parse(window.localStorage.getItem(WORKSPACE_STORAGE_KEY) || "null");
|
||
} catch (error) {
|
||
state = null;
|
||
}
|
||
|
||
try {
|
||
if (!state || state.version !== 1) return;
|
||
setCoordinateSystem(
|
||
state.settings?.coordinateSystem || state.coordinateSystem,
|
||
{ persist: false, rerender: false, notify: false }
|
||
);
|
||
setCoordinateReadoutFormat(
|
||
state.settings?.coordinateReadoutFormat || state.coordinateReadoutFormat,
|
||
{ persist: false }
|
||
);
|
||
setSidebarCollapsed(Boolean(state.layout?.sidebarCollapsed), { persist: false });
|
||
const grid = state.settings?.grid || {};
|
||
setInputValue("gridInterval", grid.interval);
|
||
setInputValue("gridIntervalUnit", grid.unit);
|
||
setInputValue("gridStartLon", grid.startLon);
|
||
setInputValue("gridStartLat", grid.startLat);
|
||
setInputValue("gridColor", grid.color);
|
||
setInputValue("gridWidth", grid.width);
|
||
|
||
const contour = state.settings?.contour || {};
|
||
setInputValue("contourInterval", contour.interval);
|
||
setInputValue("contourStart", contour.start);
|
||
setInputValue("contourBoldEvery", contour.boldEvery);
|
||
setInputValue("contourColor", contour.color);
|
||
setInputValue("contourWidth", contour.width);
|
||
setInputValue("contourBoldWidth", contour.boldWidth);
|
||
|
||
const boundarySettings = state.settings?.boundary || {};
|
||
setInputValue("boundaryHighColor", boundarySettings.highColor);
|
||
setInputValue("boundaryMiddleColor", boundarySettings.middleColor);
|
||
setInputValue("boundaryLocalColor", boundarySettings.localColor);
|
||
applyAdministrativeBoundaryControls();
|
||
Object.entries(themeColorInputs).forEach(([key, id]) => {
|
||
setInputValue(id, state.settings?.colors?.[key]);
|
||
});
|
||
const legacyRailLineStyle = state.settings?.railLineStyle;
|
||
setInputValue(
|
||
"railwayLineStyleSelect",
|
||
state.settings?.railwayLineStyle || legacyRailLineStyle || "railway"
|
||
);
|
||
setInputValue(
|
||
"metroLineStyleSelect",
|
||
state.settings?.metroLineStyle || legacyRailLineStyle || "plain"
|
||
);
|
||
applyThemeControls(true);
|
||
|
||
setInputValue("terrainProminenceThreshold", state.settings?.terrain?.threshold);
|
||
const localVectorGroups = state.settings?.localVector?.groups;
|
||
if (Array.isArray(localVectorGroups)) {
|
||
document.querySelectorAll(".local-vector-layer-toggle").forEach((input) => {
|
||
input.checked = localVectorGroups.includes(input.value);
|
||
});
|
||
}
|
||
const viewshed = state.settings?.viewshed || {};
|
||
setInputValue("viewshedHeight", viewshed.height);
|
||
setInputValue("visibilityInnerRadius", viewshed.innerRadius);
|
||
setInputValue("visibilityOuterRadius", viewshed.outerRadius);
|
||
setInputValue("visibilityNearColor", viewshed.nearColor);
|
||
setInputValue("visibilityMidColor", viewshed.midColor);
|
||
setInputValue("visibilityFarColor", viewshed.farColor);
|
||
|
||
const toggles = state.toggles || {};
|
||
setChecked("gridToggle", toggles.grid);
|
||
setChecked("contourToggle", toggles.contour);
|
||
setChecked("hillshadeToggle", toggles.hillshade);
|
||
setChecked("terrainFeatureToggle", toggles.terrain);
|
||
setChecked("terrainPeakToggle", toggles.terrainPeak);
|
||
setChecked("terrainValleyToggle", toggles.terrainValley);
|
||
setChecked("localVectorToggle", toggles.localVector);
|
||
setChecked("waterToggle", toggles.water);
|
||
setChecked("portToggle", toggles.port);
|
||
setChecked("vegetationToggle", toggles.vegetation);
|
||
setChecked("railTileToggle", toggles.railTile);
|
||
setChecked("nationalRailToggle", toggles.nationalRail);
|
||
setChecked("metroToggle", toggles.metro);
|
||
const nationalRailCategories = toggles.nationalRailCategories || {};
|
||
const metroRailCategories = toggles.metroRailCategories || {};
|
||
railCategoryKeys.forEach((key) => {
|
||
if (typeof nationalRailCategories[key] === "boolean") {
|
||
document.getElementById(nationalRailCategoryToggleIds[key]).checked =
|
||
nationalRailCategories[key];
|
||
}
|
||
if (typeof metroRailCategories[key] === "boolean") {
|
||
document.getElementById(metroRailCategoryToggleIds[key]).checked =
|
||
metroRailCategories[key];
|
||
}
|
||
});
|
||
setChecked("tdtVectorLabelToggle", toggles.tdtVectorLabel);
|
||
setChecked("tdtTerrainLabelToggle", toggles.tdtTerrainLabel);
|
||
setChecked("tdtImageryLabelToggle", toggles.tdtImageryLabel);
|
||
setChecked("tdtBoundaryToggle", toggles.tdtBoundary);
|
||
|
||
applyGridControls();
|
||
applyContourControls();
|
||
const contourOn = document.getElementById("contourToggle").checked;
|
||
setContourOptionsVisibility(contourOn);
|
||
document.getElementById("contourOptions").open = contourOn;
|
||
document.getElementById("gridOptions").open = false;
|
||
document.getElementById("gridControls").classList.toggle(
|
||
"is-disabled",
|
||
!document.getElementById("gridToggle").checked
|
||
);
|
||
setTerrainFeatureOptionsVisibility(document.getElementById("terrainFeatureToggle").checked);
|
||
updateLegendVisibility();
|
||
|
||
if (state.base && baseLayers[state.base]) setBase(state.base, { silent: true });
|
||
selectTdtLabelForBase(currentBaseKey);
|
||
const center = state.map?.center;
|
||
const zoom = Number(state.map?.zoom);
|
||
if (
|
||
Array.isArray(center) &&
|
||
Number.isFinite(Number(center[0])) &&
|
||
Number.isFinite(Number(center[1])) &&
|
||
Number.isFinite(zoom)
|
||
) {
|
||
map.setView([Number(center[0]), Number(center[1])], zoom, { animate: false });
|
||
}
|
||
|
||
setGridVisibility(document.getElementById("gridToggle").checked);
|
||
if (document.getElementById("contourToggle").checked && !map.hasLayer(contourTerrainLayer)) {
|
||
map.addLayer(contourTerrainLayer);
|
||
}
|
||
if (!document.getElementById("contourToggle").checked && map.hasLayer(contourTerrainLayer)) {
|
||
map.removeLayer(contourTerrainLayer);
|
||
}
|
||
if (document.getElementById("hillshadeToggle").checked && !map.hasLayer(hillshadeTerrainLayer)) {
|
||
map.addLayer(hillshadeTerrainLayer);
|
||
}
|
||
if (!document.getElementById("hillshadeToggle").checked && map.hasLayer(hillshadeTerrainLayer)) {
|
||
map.removeLayer(hillshadeTerrainLayer);
|
||
}
|
||
if (document.getElementById("railTileToggle").checked) {
|
||
map.addLayer(railTileLayer);
|
||
railTileLayer.setZIndex(1);
|
||
railTileStatus.hidden = false;
|
||
railTileStatus.textContent = "已显示 OpenRailwayMap 铁路基础设施。";
|
||
} else if (map.hasLayer(railTileLayer)) {
|
||
map.removeLayer(railTileLayer);
|
||
railTileStatus.hidden = true;
|
||
}
|
||
|
||
if (typeof state.print?.title === "string") {
|
||
document.getElementById("printTitleInput").value = state.print.title;
|
||
}
|
||
const frame = state.print?.frame;
|
||
if (frame && ["x", "y", "w", "h"].every((key) => Number.isFinite(Number(frame[key])))) {
|
||
frameState.x = Number(frame.x);
|
||
frameState.y = Number(frame.y);
|
||
frameState.w = Number(frame.w);
|
||
frameState.h = Number(frame.h);
|
||
hasRestoredPrintFrame = true;
|
||
}
|
||
|
||
syncRailLayers(
|
||
document.getElementById("nationalRailToggle").checked ||
|
||
document.getElementById("metroToggle").checked
|
||
);
|
||
if (document.getElementById("waterToggle").checked ||
|
||
document.getElementById("portToggle").checked ||
|
||
document.getElementById("vegetationToggle").checked) {
|
||
void loadWaterData();
|
||
}
|
||
document.getElementById("localVectorOptions").hidden =
|
||
!document.getElementById("localVectorToggle").checked;
|
||
if (document.getElementById("localVectorToggle").checked) {
|
||
map.addLayer(localVectorLayer);
|
||
void loadLocalVectorData();
|
||
}
|
||
if (document.getElementById("tdtBoundaryToggle").checked) {
|
||
map.addLayer(administrativeBoundaryLayer);
|
||
void loadAdministrativeBoundaryData();
|
||
}
|
||
updateReadout();
|
||
} finally {
|
||
isRestoringWorkspace = false;
|
||
scheduleTerrainFeatureUpdate();
|
||
}
|
||
};
|
||
|
||
document.getElementById("printTitleInput").addEventListener("input", scheduleWorkspaceSave);
|
||
document.getElementById("printTitleInput").addEventListener("change", scheduleWorkspaceSave);
|
||
|
||
document.getElementById("pathDrawButton").addEventListener("click", () => startDrawing("path"));
|
||
document.getElementById("rangeDrawButton").addEventListener("click", () => startDrawing("range"));
|
||
document.getElementById("viewshedButton").addEventListener("click", () => startDrawing("viewshed"));
|
||
document.getElementById("visibilityObservationButton").addEventListener("click", () => startDrawing("observation"));
|
||
document.getElementById("finishDrawingButton").addEventListener("click", finishDrawing);
|
||
document.getElementById("clearDrawButton").addEventListener("click", clearAllDrawings);
|
||
|
||
document.getElementById("exportProjectButton").addEventListener("click", exportProjectFile);
|
||
document.getElementById("importProjectButton").addEventListener("click", () => {
|
||
document.getElementById("importProjectInput").click();
|
||
});
|
||
document.getElementById("importProjectInput").addEventListener("change", async (event) => {
|
||
const input = event.target;
|
||
const file = input.files && input.files[0];
|
||
if (!file) return;
|
||
try {
|
||
await importProjectFile(file);
|
||
} catch (error) {
|
||
showToast(error.message || "工程文件导入失败。", "error");
|
||
input.value = "";
|
||
}
|
||
});
|
||
|
||
document.querySelectorAll(".base-card").forEach((button) => {
|
||
button.addEventListener("click", () => {
|
||
setBase(button.dataset.base);
|
||
selectTdtLabelForBase(button.dataset.base, { force: true });
|
||
scheduleWorkspaceSave();
|
||
});
|
||
});
|
||
|
||
document.getElementById("hillshadeToggle").addEventListener("change", (event) => {
|
||
if (event.target.checked) {
|
||
map.addLayer(hillshadeTerrainLayer);
|
||
showToast("地形晕渲已叠加到当前底图。");
|
||
} else {
|
||
map.removeLayer(hillshadeTerrainLayer);
|
||
showToast("已隐藏地形晕渲叠加层。");
|
||
}
|
||
updateLegendVisibility();
|
||
scheduleWorkspaceSave();
|
||
});
|
||
|
||
document.getElementById("contourToggle").addEventListener("change", (event) => {
|
||
const contourOn = event.target.checked;
|
||
setContourOptionsVisibility(contourOn);
|
||
document.getElementById("contourOptions").open = contourOn;
|
||
if (contourOn) {
|
||
map.addLayer(contourTerrainLayer);
|
||
showToast("等高线已叠加到当前底图。");
|
||
} else {
|
||
map.removeLayer(contourTerrainLayer);
|
||
showToast("已隐藏等高线叠加层。");
|
||
}
|
||
updateLegendVisibility();
|
||
scheduleWorkspaceSave();
|
||
});
|
||
|
||
["contourInterval", "contourStart", "contourBoldEvery", "contourColor", "contourWidth", "contourBoldWidth"].forEach((id) => {
|
||
document.getElementById(id).addEventListener("input", applyContourControls);
|
||
document.getElementById(id).addEventListener("change", applyContourControls);
|
||
});
|
||
setContourOptionsVisibility(false);
|
||
applyContourControls();
|
||
|
||
["gridInterval", "gridIntervalUnit", "gridStartLon", "gridStartLat", "gridColor", "gridWidth"].forEach((id) => {
|
||
document.getElementById(id).addEventListener("input", applyGridControls);
|
||
document.getElementById(id).addEventListener("change", applyGridControls);
|
||
});
|
||
applyGridControls();
|
||
["boundaryHighColor", "boundaryMiddleColor", "boundaryLocalColor"].forEach((id) => {
|
||
document.getElementById(id).addEventListener("input", () => {
|
||
applyAdministrativeBoundaryControls();
|
||
scheduleWorkspaceSave();
|
||
});
|
||
document.getElementById(id).addEventListener("change", () => {
|
||
applyAdministrativeBoundaryControls();
|
||
scheduleWorkspaceSave();
|
||
});
|
||
});
|
||
applyAdministrativeBoundaryControls();
|
||
|
||
let themeRenderTimer = null;
|
||
const applyThemeControls = (refreshLayers = true) => {
|
||
Object.entries(themeColorInputs).forEach(([key, id]) => {
|
||
const input = document.getElementById(id);
|
||
if (input) themeColors[key] = input.value;
|
||
});
|
||
railwayLineStyle = document.getElementById("railwayLineStyleSelect").value === "plain"
|
||
? "plain"
|
||
: "railway";
|
||
metroLineStyle = document.getElementById("metroLineStyleSelect").value === "railway"
|
||
? "railway"
|
||
: "plain";
|
||
document.documentElement.style.setProperty("--terrain-peak-color", themeColors.terrainPeak);
|
||
document.documentElement.style.setProperty("--terrain-valley-color", themeColors.terrainValley);
|
||
updateLegendVisibility();
|
||
if (!refreshLayers) return;
|
||
window.clearTimeout(themeRenderTimer);
|
||
themeRenderTimer = window.setTimeout(() => {
|
||
if (loadedRailElements.length &&
|
||
(document.getElementById("nationalRailToggle").checked ||
|
||
document.getElementById("metroToggle").checked)) {
|
||
renderRailElements(loadedRailElements, { replace: true });
|
||
}
|
||
if (localVectorFeatures.length && document.getElementById("localVectorToggle").checked) {
|
||
renderLocalVectorFeatures(localVectorFeatures);
|
||
}
|
||
if (loadedWaterElements.length && document.getElementById("waterToggle").checked) {
|
||
renderWaterElements(loadedWaterElements);
|
||
}
|
||
if (loadedPortElements.length && document.getElementById("portToggle").checked) {
|
||
renderPortElements(loadedPortElements);
|
||
}
|
||
if (loadedVegetationElements.length && document.getElementById("vegetationToggle").checked) {
|
||
renderVegetationElements(loadedVegetationElements);
|
||
}
|
||
}, 80);
|
||
};
|
||
|
||
Object.values(themeColorInputs).forEach((id) => {
|
||
const input = document.getElementById(id);
|
||
input.addEventListener("input", () => applyThemeControls(false));
|
||
input.addEventListener("change", () => {
|
||
applyThemeControls(true);
|
||
scheduleWorkspaceSave();
|
||
});
|
||
});
|
||
document.getElementById("railwayLineStyleSelect").addEventListener("change", () => {
|
||
applyThemeControls(true);
|
||
scheduleWorkspaceSave();
|
||
});
|
||
document.getElementById("metroLineStyleSelect").addEventListener("change", () => {
|
||
applyThemeControls(true);
|
||
scheduleWorkspaceSave();
|
||
});
|
||
|
||
const applyVisibilityColors = () => {
|
||
const colors = {
|
||
near: document.getElementById("visibilityNearColor").value,
|
||
mid: document.getElementById("visibilityMidColor").value,
|
||
far: document.getElementById("visibilityFarColor").value
|
||
};
|
||
drawingItems
|
||
.filter((item) => item.type === "observation" && item.areaLayer)
|
||
.forEach((item) => {
|
||
if (item.customColor) {
|
||
item.areaLayer.setColors({
|
||
near: item.color,
|
||
mid: item.color,
|
||
far: item.color
|
||
});
|
||
return;
|
||
}
|
||
item.colorBands = { ...colors };
|
||
if (item.observation) item.observation.colorBands = { ...colors };
|
||
item.areaLayer.setColors(colors);
|
||
});
|
||
updateLegendVisibility();
|
||
scheduleDrawingSave();
|
||
scheduleWorkspaceSave();
|
||
};
|
||
["visibilityNearColor", "visibilityMidColor", "visibilityFarColor"].forEach((id) => {
|
||
document.getElementById(id).addEventListener("input", applyVisibilityColors);
|
||
document.getElementById(id).addEventListener("change", applyVisibilityColors);
|
||
});
|
||
["viewshedHeight", "visibilityInnerRadius", "visibilityOuterRadius"].forEach((id) => {
|
||
document.getElementById(id).addEventListener("input", scheduleWorkspaceSave);
|
||
document.getElementById(id).addEventListener("change", scheduleWorkspaceSave);
|
||
});
|
||
|
||
document.getElementById("railTileToggle").addEventListener("change", (event) => {
|
||
if (event.target.checked) {
|
||
map.addLayer(railTileLayer);
|
||
railTileLayer.setZIndex(1);
|
||
railTileStatus.hidden = false;
|
||
railTileStatus.textContent = "已显示 OpenRailwayMap 铁路基础设施。";
|
||
if (!document.getElementById("nationalRailToggle").checked &&
|
||
!document.getElementById("metroToggle").checked) {
|
||
railStatus.textContent = "铁路基础设施已显示;国铁、地铁矢量未开启。";
|
||
}
|
||
} else {
|
||
map.removeLayer(railTileLayer);
|
||
railTileStatus.hidden = true;
|
||
if (!document.getElementById("nationalRailToggle").checked &&
|
||
!document.getElementById("metroToggle").checked) {
|
||
railStatus.textContent = "铁路图层均已关闭。";
|
||
}
|
||
}
|
||
scheduleWorkspaceSave();
|
||
updateLegendVisibility();
|
||
showToast(event.target.checked ? "已显示铁路基础设施瓦片。" : "已隐藏铁路基础设施瓦片。");
|
||
});
|
||
|
||
document.getElementById("gridToggle").addEventListener("change", (event) => {
|
||
const gridOn = event.target.checked;
|
||
document.getElementById("gridOptions").open = gridOn;
|
||
document.getElementById("gridControls").classList.toggle("is-disabled", !gridOn);
|
||
setGridVisibility(gridOn);
|
||
updateLegendVisibility();
|
||
scheduleWorkspaceSave();
|
||
showToast(gridOn ? "已显示经纬网格。" : "已隐藏经纬网格。");
|
||
});
|
||
document.getElementById("terrainFeatureToggle").addEventListener("change", (event) => {
|
||
setTerrainFeatureOptionsVisibility(event.target.checked);
|
||
updateLegendVisibility();
|
||
scheduleTerrainFeatureUpdate();
|
||
scheduleWorkspaceSave();
|
||
});
|
||
["terrainPeakToggle", "terrainValleyToggle"].forEach((id) => {
|
||
document.getElementById(id).addEventListener("change", () => {
|
||
updateLegendVisibility();
|
||
scheduleTerrainFeatureUpdate();
|
||
scheduleWorkspaceSave();
|
||
});
|
||
});
|
||
["input", "change"].forEach((eventName) => {
|
||
document.getElementById("terrainProminenceThreshold").addEventListener(eventName, () => {
|
||
scheduleTerrainFeatureUpdate();
|
||
scheduleWorkspaceSave();
|
||
});
|
||
});
|
||
|
||
document.getElementById("localVectorToggle").addEventListener("change", (event) => {
|
||
document.getElementById("localVectorOptions").hidden = !event.target.checked;
|
||
document.getElementById("localVectorOptions").open = event.target.checked;
|
||
if (event.target.checked) {
|
||
map.addLayer(localVectorLayer);
|
||
void loadLocalVectorData();
|
||
showToast("已开启天地图图素。");
|
||
} else {
|
||
window.clearTimeout(localVectorRefreshTimer);
|
||
localVectorLoadSequence += 1;
|
||
localVectorFeatures = [];
|
||
localVectorLayer.clearLayers();
|
||
map.removeLayer(localVectorLayer);
|
||
if (localVectorStatus) localVectorStatus.textContent = "开启后加载当前视窗的本地矢量数据。";
|
||
showToast("已隐藏天地图图素。");
|
||
}
|
||
updateLegendVisibility();
|
||
scheduleWorkspaceSave();
|
||
});
|
||
document.querySelectorAll(".local-vector-layer-toggle").forEach((input) => {
|
||
input.addEventListener("change", () => {
|
||
if (document.getElementById("localVectorToggle").checked && !localVectorFeatures.length) {
|
||
void loadLocalVectorData();
|
||
} else {
|
||
const counts = renderLocalVectorFeatures(localVectorFeatures);
|
||
updateLocalVectorStatus(counts, "当前视窗");
|
||
}
|
||
updateLegendVisibility();
|
||
scheduleWorkspaceSave();
|
||
});
|
||
});
|
||
|
||
document.getElementById("waterToggle").addEventListener("change", (event) => {
|
||
window.clearTimeout(waterRefreshTimer);
|
||
window.clearTimeout(waterPendingPollTimer);
|
||
if (event.target.checked) {
|
||
map.addLayer(waterLayerGroup);
|
||
waterStatus.hidden = false;
|
||
waterStatus.textContent = "正在加载当前视窗…";
|
||
} else {
|
||
map.removeLayer(waterLayerGroup);
|
||
waterStatus.hidden = true;
|
||
}
|
||
const anyEnvironmentLayer =
|
||
event.target.checked ||
|
||
document.getElementById("portToggle").checked ||
|
||
document.getElementById("vegetationToggle").checked;
|
||
if (anyEnvironmentLayer) {
|
||
void loadWaterData();
|
||
} else {
|
||
waterStatus.hidden = true;
|
||
portStatus.hidden = true;
|
||
vegetationStatus.hidden = true;
|
||
}
|
||
updateLegendVisibility();
|
||
scheduleWorkspaceSave();
|
||
});
|
||
|
||
["portToggle", "vegetationToggle"].forEach((id) => {
|
||
document.getElementById(id).addEventListener("change", () => {
|
||
window.clearTimeout(waterRefreshTimer);
|
||
window.clearTimeout(waterPendingPollTimer);
|
||
const portOn = document.getElementById("portToggle").checked;
|
||
const vegetationOn = document.getElementById("vegetationToggle").checked;
|
||
if (portOn) {
|
||
map.addLayer(portLayerGroup);
|
||
portStatus.hidden = false;
|
||
portStatus.textContent = "正在加载当前视窗…";
|
||
} else {
|
||
map.removeLayer(portLayerGroup);
|
||
portStatus.hidden = true;
|
||
}
|
||
if (vegetationOn) {
|
||
map.addLayer(vegetationLayerGroup);
|
||
vegetationStatus.hidden = false;
|
||
vegetationStatus.textContent = "正在加载当前视窗…";
|
||
} else {
|
||
map.removeLayer(vegetationLayerGroup);
|
||
vegetationStatus.hidden = true;
|
||
}
|
||
if (portOn || vegetationOn || document.getElementById("waterToggle").checked) {
|
||
void loadWaterData();
|
||
} else {
|
||
waterStatus.hidden = true;
|
||
portStatus.hidden = true;
|
||
vegetationStatus.hidden = true;
|
||
}
|
||
updateLegendVisibility();
|
||
scheduleWorkspaceSave();
|
||
});
|
||
});
|
||
|
||
Object.keys(tdtOverlayLayers).forEach((id) => {
|
||
document.getElementById(id).addEventListener("change", () => {
|
||
if (tdtLabelToggleIds.includes(id) && document.getElementById(id).checked) {
|
||
tdtLabelToggleIds
|
||
.filter((labelToggleId) => labelToggleId !== id)
|
||
.forEach((labelToggleId) => {
|
||
document.getElementById(labelToggleId).checked = false;
|
||
});
|
||
}
|
||
syncTdtOverlayLayers();
|
||
scheduleWorkspaceSave();
|
||
});
|
||
});
|
||
document.getElementById("tdtBoundaryToggle").addEventListener("change", (event) => {
|
||
if (event.target.checked) {
|
||
map.addLayer(administrativeBoundaryLayer);
|
||
void loadAdministrativeBoundaryData();
|
||
showToast("已开启行政区划:国界、省界、地级界和县级界。");
|
||
} else {
|
||
window.clearTimeout(boundaryRefreshTimer);
|
||
boundaryLoadSequence += 1;
|
||
administrativeBoundaryLayer.clearLayers();
|
||
lastAdministrativeBoundaryElements = [];
|
||
map.removeLayer(administrativeBoundaryLayer);
|
||
if (boundaryStatus) boundaryStatus.textContent = "开启后加载当前视窗的省、地级和县级行政边界。";
|
||
showToast("已隐藏行政区划。");
|
||
}
|
||
updateLegendVisibility();
|
||
});
|
||
|
||
document.getElementById("nationalRailToggle").addEventListener("change", () => {
|
||
syncRailLayers(true);
|
||
scheduleWorkspaceSave();
|
||
});
|
||
document.getElementById("metroToggle").addEventListener("change", () => {
|
||
syncRailLayers(true);
|
||
scheduleWorkspaceSave();
|
||
});
|
||
[
|
||
...Object.values(nationalRailCategoryToggleIds),
|
||
...Object.values(metroRailCategoryToggleIds)
|
||
].forEach((id) => {
|
||
document.getElementById(id).addEventListener("change", () => {
|
||
scheduleWorkspaceSave();
|
||
if (document.getElementById("nationalRailToggle").checked ||
|
||
document.getElementById("metroToggle").checked) {
|
||
void loadRailData();
|
||
}
|
||
});
|
||
});
|
||
document.getElementById("refreshRailButton").addEventListener("click", () => loadRailData({ force: true }));
|
||
|
||
document.getElementById("resetLayers").addEventListener("click", (event) => {
|
||
event.stopPropagation();
|
||
previousBaseBeforeContour = "clean";
|
||
document.getElementById("hillshadeToggle").checked = false;
|
||
setBase("clean", { silent: true });
|
||
document.getElementById("contourToggle").checked = false;
|
||
setContourOptionsVisibility(false);
|
||
if (map.hasLayer(contourTerrainLayer)) map.removeLayer(contourTerrainLayer);
|
||
document.getElementById("contourInterval").value = "20";
|
||
document.getElementById("contourStart").value = "0";
|
||
document.getElementById("contourBoldEvery").value = "5";
|
||
document.getElementById("contourColor").value = "#76512d";
|
||
document.getElementById("contourWidth").value = "1";
|
||
document.getElementById("contourBoldWidth").value = "2.2";
|
||
applyContourControls();
|
||
document.getElementById("railTileToggle").checked = false;
|
||
document.getElementById("nationalRailToggle").checked = false;
|
||
document.getElementById("metroToggle").checked = false;
|
||
[nationalRailCategoryToggleIds, metroRailCategoryToggleIds].forEach((toggleIds) => {
|
||
railCategoryKeys.forEach((key) => {
|
||
document.getElementById(toggleIds[key]).checked =
|
||
key === "main" || key === "highSpeed";
|
||
});
|
||
});
|
||
document.getElementById("terrainFeatureToggle").checked = false;
|
||
document.getElementById("localVectorToggle").checked = false;
|
||
document.getElementById("localVectorOptions").hidden = true;
|
||
localVectorLoadSequence += 1;
|
||
localVectorFeatures = [];
|
||
localVectorLayer.clearLayers();
|
||
if (map.hasLayer(localVectorLayer)) map.removeLayer(localVectorLayer);
|
||
if (localVectorStatus) localVectorStatus.textContent = "开启后加载当前视窗的本地矢量数据。";
|
||
document.getElementById("waterToggle").checked = false;
|
||
document.getElementById("portToggle").checked = false;
|
||
document.getElementById("vegetationToggle").checked = false;
|
||
document.getElementById("tdtVectorLabelToggle").checked = false;
|
||
document.getElementById("tdtTerrainLabelToggle").checked = false;
|
||
document.getElementById("tdtImageryLabelToggle").checked = false;
|
||
document.getElementById("tdtBoundaryToggle").checked = false;
|
||
boundaryLoadSequence += 1;
|
||
administrativeBoundaryLayer.clearLayers();
|
||
lastAdministrativeBoundaryElements = [];
|
||
document.getElementById("boundaryHighColor").value = "#8f2e1f";
|
||
document.getElementById("boundaryMiddleColor").value = "#bd4f2e";
|
||
document.getElementById("boundaryLocalColor").value = "#d47a2c";
|
||
applyAdministrativeBoundaryControls();
|
||
const defaultThemeColors = {
|
||
national: "#5c43c6",
|
||
metro: "#e15b3c",
|
||
water: "#4fb6dc",
|
||
port: "#166a86",
|
||
vegetation: "#68a94f",
|
||
terrainPeak: "#a45d2c",
|
||
terrainValley: "#2e628d",
|
||
localRoads: "#d16a35",
|
||
localRailways: "#6847a6",
|
||
localWater: "#378db7",
|
||
localAdministration: "#98462e",
|
||
localSettlements: "#795334",
|
||
localVegetation: "#4a8050",
|
||
localTerrain: "#84633f",
|
||
localFacilities: "#8b7358",
|
||
localHeritage: "#a4544f"
|
||
};
|
||
Object.entries(themeColorInputs).forEach(([key, id]) => {
|
||
document.getElementById(id).value = defaultThemeColors[key];
|
||
});
|
||
document.getElementById("railwayLineStyleSelect").value = "railway";
|
||
document.getElementById("metroLineStyleSelect").value = "plain";
|
||
applyThemeControls(true);
|
||
if (map.hasLayer(administrativeBoundaryLayer)) map.removeLayer(administrativeBoundaryLayer);
|
||
if (boundaryStatus) boundaryStatus.textContent = "开启后加载当前视窗的省、地级和县级行政边界。";
|
||
document.getElementById("terrainPeakToggle").checked = true;
|
||
document.getElementById("terrainValleyToggle").checked = true;
|
||
document.getElementById("terrainProminenceThreshold").value = "30";
|
||
setTerrainFeatureOptionsVisibility(false);
|
||
document.getElementById("terrainFeatureOptions").open = false;
|
||
document.getElementById("gridToggle").checked = true;
|
||
document.getElementById("gridToggle").disabled = false;
|
||
document.getElementById("gridControls").classList.remove("is-disabled");
|
||
document.getElementById("gridInterval").value = "";
|
||
document.getElementById("gridIntervalUnit").value = "degree";
|
||
document.getElementById("gridStartLon").value = "0";
|
||
document.getElementById("gridStartLat").value = "0";
|
||
document.getElementById("gridColor").value = "#2f5543";
|
||
document.getElementById("gridWidth").value = "0.7";
|
||
applyGridControls();
|
||
document.getElementById("gridOptions").open = false;
|
||
document.getElementById("contourOptions").open = false;
|
||
setGridVisibility(true);
|
||
|
||
if (map.hasLayer(railTileLayer)) map.removeLayer(railTileLayer);
|
||
if (!map.hasLayer(gridLayer)) map.addLayer(gridLayer);
|
||
map.removeLayer(nationalRailGroup);
|
||
map.removeLayer(metroGroup);
|
||
terrainFeatureLayer.clearLayers();
|
||
if (map.hasLayer(terrainFeatureLayer)) map.removeLayer(terrainFeatureLayer);
|
||
waterLayerGroup.clearLayers();
|
||
renderedWaterFeatureIds = new Set();
|
||
if (map.hasLayer(waterLayerGroup)) map.removeLayer(waterLayerGroup);
|
||
portLayerGroup.clearLayers();
|
||
renderedPortFeatureIds = new Set();
|
||
if (map.hasLayer(portLayerGroup)) map.removeLayer(portLayerGroup);
|
||
vegetationLayerGroup.clearLayers();
|
||
renderedVegetationFeatureIds = new Set();
|
||
if (map.hasLayer(vegetationLayerGroup)) map.removeLayer(vegetationLayerGroup);
|
||
syncTdtOverlayLayers();
|
||
window.clearTimeout(waterRefreshTimer);
|
||
window.clearTimeout(waterPendingPollTimer);
|
||
waterStatus.hidden = true;
|
||
portStatus.hidden = true;
|
||
vegetationStatus.hidden = true;
|
||
nationalRailGroup.clearLayers();
|
||
metroGroup.clearLayers();
|
||
railStatus.textContent = "铁路矢量图层尚未加载。";
|
||
railTileStatus.hidden = true;
|
||
nationalRailStatus.hidden = true;
|
||
metroStatus.hidden = true;
|
||
scheduleTerrainFeatureUpdate();
|
||
updateLegendVisibility();
|
||
scheduleWorkspaceSave();
|
||
showToast("图层已重置。");
|
||
updateReadout();
|
||
});
|
||
|
||
document.querySelectorAll("[data-place]").forEach((button) => {
|
||
button.addEventListener("click", () => {
|
||
const values = button.dataset.place.split(",").map(Number);
|
||
map.flyTo([values[0], values[1]], values[2], { duration: 1.1 });
|
||
});
|
||
});
|
||
|
||
document.getElementById("zoomInButton").addEventListener("click", () => map.zoomIn());
|
||
document.getElementById("zoomOutButton").addEventListener("click", () => map.zoomOut());
|
||
document.getElementById("homeButton").addEventListener("click", () => {
|
||
map.flyTo(DEFAULT_VIEW.center, DEFAULT_VIEW.zoom, { duration: 1.1 });
|
||
});
|
||
|
||
sidebarToggleButton.addEventListener("click", () => {
|
||
if (compactSidebarMedia.matches) {
|
||
layerSidebar.classList.toggle("open");
|
||
refreshSidebarToggleState();
|
||
window.requestAnimationFrame(() => map.invalidateSize({ animate: false, pan: false }));
|
||
scheduleWorkspaceSave();
|
||
} else {
|
||
setSidebarCollapsed(!appShell.classList.contains("sidebar-collapsed"));
|
||
}
|
||
});
|
||
|
||
compactSidebarMedia.addEventListener("change", () => {
|
||
refreshSidebarToggleState();
|
||
window.requestAnimationFrame(() => map.invalidateSize({ animate: false, pan: false }));
|
||
});
|
||
|
||
document.getElementById("locateButton").addEventListener("click", () => {
|
||
setStatus("正在获取设备位置…", "busy");
|
||
map.locate({ setView: true, maxZoom: 14, timeout: 10000, enableHighAccuracy: true });
|
||
});
|
||
|
||
map.on("locationfound", (event) => {
|
||
L.circleMarker(event.latlng, {
|
||
radius: 7,
|
||
color: "#ffffff",
|
||
weight: 3,
|
||
fillColor: "#205c46",
|
||
fillOpacity: 1
|
||
}).addTo(map).bindPopup("当前位置").openPopup();
|
||
setStatus("地图已就绪");
|
||
});
|
||
|
||
map.on("locationerror", () => {
|
||
setStatus("无法获取设备位置", "error");
|
||
showToast("浏览器未允许定位,或当前页面环境不支持定位。", "error");
|
||
});
|
||
|
||
map.on("mousemove", (event) => {
|
||
updateReadout(event.latlng);
|
||
window.clearTimeout(elevationTimer);
|
||
const request = ++elevationRequest;
|
||
const position = event.latlng;
|
||
elevationTimer = window.setTimeout(async () => {
|
||
try {
|
||
const elevation = await getElevationAt(position);
|
||
if (request === elevationRequest && Number.isFinite(elevation)) {
|
||
document.getElementById("elevationReadout").textContent = "高程 " + elevation.toFixed(1) + " m";
|
||
}
|
||
} catch (error) {
|
||
if (request === elevationRequest) document.getElementById("elevationReadout").textContent = "高程 —";
|
||
}
|
||
}, 140);
|
||
});
|
||
map.on("zoomend moveend", () => {
|
||
updateReadout();
|
||
updatePrintDecor();
|
||
scheduleWorkspaceSave();
|
||
if (document.getElementById("terrainFeatureToggle").checked) scheduleTerrainFeatureUpdate();
|
||
if (document.getElementById("tdtBoundaryToggle").checked) {
|
||
window.clearTimeout(boundaryRefreshTimer);
|
||
boundaryRefreshTimer = window.setTimeout(() => {
|
||
if (document.getElementById("tdtBoundaryToggle").checked) {
|
||
void loadAdministrativeBoundaryData();
|
||
}
|
||
}, 700);
|
||
}
|
||
if (document.getElementById("localVectorToggle").checked) {
|
||
window.clearTimeout(localVectorRefreshTimer);
|
||
localVectorRefreshTimer = window.setTimeout(() => {
|
||
if (document.getElementById("localVectorToggle").checked) {
|
||
void loadLocalVectorData();
|
||
}
|
||
}, 650);
|
||
}
|
||
});
|
||
|
||
let railRefreshTimer = null;
|
||
map.on("moveend", () => {
|
||
const anyRailVectorActive =
|
||
document.getElementById("nationalRailToggle").checked ||
|
||
document.getElementById("metroToggle").checked;
|
||
if (!anyRailVectorActive) return;
|
||
|
||
window.clearTimeout(railRefreshTimer);
|
||
railRefreshTimer = window.setTimeout(() => {
|
||
if (!document.getElementById("nationalRailToggle").checked &&
|
||
!document.getElementById("metroToggle").checked) return;
|
||
railStatus.textContent = "视窗已变化,正在匹配当前视窗铁路…";
|
||
syncRailLayers(true);
|
||
}, 900);
|
||
});
|
||
map.on("moveend", scheduleWorkspaceSave);
|
||
map.on("moveend", () => {
|
||
if (!document.getElementById("waterToggle").checked &&
|
||
!document.getElementById("portToggle").checked &&
|
||
!document.getElementById("vegetationToggle").checked) return;
|
||
window.clearTimeout(waterRefreshTimer);
|
||
waterRefreshTimer = window.setTimeout(() => {
|
||
if (document.getElementById("waterToggle").checked ||
|
||
document.getElementById("portToggle").checked ||
|
||
document.getElementById("vegetationToggle").checked) {
|
||
void loadWaterData();
|
||
}
|
||
}, 900);
|
||
});
|
||
|
||
let pendingProjectImportNotice = null;
|
||
try {
|
||
pendingProjectImportNotice = window.sessionStorage.getItem(PROJECT_IMPORT_NOTICE_KEY);
|
||
if (pendingProjectImportNotice) {
|
||
window.sessionStorage.removeItem(PROJECT_IMPORT_NOTICE_KEY);
|
||
}
|
||
} catch (error) {
|
||
// Session storage may be unavailable; the imported project itself is still restored.
|
||
}
|
||
|
||
restoreWorkspaceState();
|
||
updateLegendVisibility();
|
||
applyThemeControls(true);
|
||
refreshSidebarToggleState();
|
||
restoreDrawingsFromStorage();
|
||
if (pendingProjectImportNotice) {
|
||
window.setTimeout(() => showToast(pendingProjectImportNotice), 250);
|
||
}
|
||
|
||
// An imported project is the complete source of truth. URL parameters are
|
||
// still honoured for normal launches, but must not override imported state.
|
||
const urlParams = pendingProjectImportNotice
|
||
? new URLSearchParams()
|
||
: new URLSearchParams(window.location.search);
|
||
const requestedBase = urlParams.get('base');
|
||
const requestedCoordinateSystem = urlParams.get('crs') || urlParams.get('coordinateSystem');
|
||
const requestedLat = Number(urlParams.get('lat'));
|
||
const requestedLon = Number(urlParams.get('lon'));
|
||
const requestedZoom = Number(urlParams.get('zoom'));
|
||
if (urlParams.get('sidebar') === '0') setSidebarCollapsed(true, { persist: false });
|
||
if (urlParams.get('sidebar') === '1') setSidebarCollapsed(false, { persist: false });
|
||
if (requestedCoordinateSystem) {
|
||
setCoordinateSystem(requestedCoordinateSystem, {
|
||
persist: false,
|
||
rerender: false,
|
||
notify: false
|
||
});
|
||
}
|
||
if (requestedBase && baseLayers[requestedBase]) {
|
||
setBase(requestedBase, { silent: true });
|
||
selectTdtLabelForBase(currentBaseKey, { force: true });
|
||
}
|
||
const requestedHillshade = urlParams.get("hillshade");
|
||
if (requestedHillshade === "1" || requestedHillshade === "0") {
|
||
const hillshadeEnabled = requestedHillshade === "1";
|
||
document.getElementById("hillshadeToggle").checked = hillshadeEnabled;
|
||
if (hillshadeEnabled && !map.hasLayer(hillshadeTerrainLayer)) {
|
||
map.addLayer(hillshadeTerrainLayer);
|
||
}
|
||
if (!hillshadeEnabled && map.hasLayer(hillshadeTerrainLayer)) {
|
||
map.removeLayer(hillshadeTerrainLayer);
|
||
}
|
||
}
|
||
const requestedRailStyle = urlParams.get("railstyle");
|
||
if (requestedRailStyle === "plain" || requestedRailStyle === "railway") {
|
||
document.getElementById("railwayLineStyleSelect").value = requestedRailStyle;
|
||
applyThemeControls(true);
|
||
}
|
||
const requestedMetroStyle = urlParams.get("metrostyle");
|
||
if (requestedMetroStyle === "plain" || requestedMetroStyle === "railway") {
|
||
document.getElementById("metroLineStyleSelect").value = requestedMetroStyle;
|
||
applyThemeControls(true);
|
||
}
|
||
if (urlParams.get('contour') === '1') {
|
||
document.getElementById('contourToggle').checked = true;
|
||
setContourOptionsVisibility(true);
|
||
document.getElementById('contourOptions').open = true;
|
||
map.addLayer(contourTerrainLayer);
|
||
|
||
}
|
||
if (urlParams.get('grid') === '0') {
|
||
document.getElementById('gridToggle').checked = false;
|
||
setGridVisibility(false);
|
||
}
|
||
if (urlParams.get('rail') === '1') {
|
||
document.getElementById('nationalRailToggle').checked = true;
|
||
document.getElementById('metroToggle').checked = true;
|
||
syncRailLayers(true);
|
||
}
|
||
if (urlParams.get('water') === '1') {
|
||
document.getElementById('waterToggle').checked = true;
|
||
map.addLayer(waterLayerGroup);
|
||
void loadWaterData();
|
||
}
|
||
if (urlParams.get('port') === '1') {
|
||
document.getElementById('portToggle').checked = true;
|
||
map.addLayer(portLayerGroup);
|
||
void loadWaterData();
|
||
}
|
||
if (urlParams.get('vegetation') === '1') {
|
||
document.getElementById('vegetationToggle').checked = true;
|
||
map.addLayer(vegetationLayerGroup);
|
||
void loadWaterData();
|
||
}
|
||
if (urlParams.get('localvector') === '1') {
|
||
document.getElementById('localVectorToggle').checked = true;
|
||
document.getElementById('localVectorOptions').hidden = false;
|
||
map.addLayer(localVectorLayer);
|
||
void loadLocalVectorData();
|
||
}
|
||
if (urlParams.get('tdt') === '1') {
|
||
const preferredLabelToggle =
|
||
tdtLabelToggleByBase[requestedBase] ||
|
||
tdtLabelToggleByBase[currentBaseKey] ||
|
||
"tdtVectorLabelToggle";
|
||
tdtLabelToggleIds.forEach((id) => {
|
||
document.getElementById(id).checked = id === preferredLabelToggle;
|
||
});
|
||
document.getElementById("tdtBoundaryToggle").checked = true;
|
||
}
|
||
syncTdtOverlayLayers();
|
||
if (document.getElementById("tdtBoundaryToggle").checked) {
|
||
map.addLayer(administrativeBoundaryLayer);
|
||
void loadAdministrativeBoundaryData();
|
||
}
|
||
const hasRequestedView = urlParams.has('lat') && urlParams.has('lon') && urlParams.has('zoom');
|
||
if (hasRequestedView && Number.isFinite(requestedLat) && Number.isFinite(requestedLon) && Number.isFinite(requestedZoom) && requestedZoom > 0) {
|
||
map.setView([requestedLat, requestedLon], requestedZoom);
|
||
}
|
||
|
||
if (urlParams.get('print') === '1') setPrintMode(true);
|
||
|
||
window.addEventListener("scroll", () => window.scrollTo(0, 0));
|
||
window.addEventListener("resize", () => {
|
||
window.scrollTo(0, 0);
|
||
if (document.body.classList.contains("print-mode")) updatePrintPreviewScale();
|
||
map.invalidateSize({ animate: false, pan: false });
|
||
updatePrintDecor();
|
||
});
|
||
window.addEventListener("afterprint", () => {
|
||
window.requestAnimationFrame(() => {
|
||
map.invalidateSize({ animate: false, pan: false });
|
||
updatePrintDecor();
|
||
window.scrollTo(0, 0);
|
||
});
|
||
});
|
||
|
||
window.addEventListener("pagehide", () => {
|
||
saveWorkspaceNow();
|
||
saveDrawingsNow();
|
||
});
|
||
document.addEventListener("visibilitychange", () => {
|
||
if (document.visibilityState === "hidden") {
|
||
saveWorkspaceNow();
|
||
saveDrawingsNow();
|
||
}
|
||
});
|
||
|
||
scheduleTerrainFeatureUpdate();
|
||
updateReadout();
|
||
scheduleWorkspaceSave();
|
||
void checkMapService(false);
|
||
})();
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|