Color-code, cluster and add icons to POI waypoints
A park4night/OsmAnd POI export (e.g. a p4n2gpx area export) tags every waypoint with a category and a per-category color/icon in its <extensions> block, all of which was previously thrown away — every waypoint rendered as the same plain red dot, unreadable once a file has a few thousand of them. Maptool::Gpx now captures category/color/icon (waypoint_style), matched by namespace URI rather than local element name: a p4n2gpx file carries both <osmand:icon> and <locus:icon> side by side, and REXML strips prefixes from Element#name, so both report as just "icon" — matching on that alone was silently picking the (useless) Locus drawable path instead of the OsmAnd category key. Regression test added for this. On the map: waypoints are colored by category (falling back to the plain track color for anything uncategorized), a small hand-drawn icon set (public/js/icons.js's POI_ICONS, rasterized to SDF sprites at runtime) draws a glyph on top for the categories it covers, the points source is clustered so a dense export collapses into count bubbles instead of a solid blob, and a legend in the side panel lists whichever categories are currently visible. Splitting each file's GeoJSON into a lines source and a points source (rather than one mixed source with a geometry-type filter per layer) was needed for clustering, since MapLibre's cluster support only understands a source made entirely of points.
This commit is contained in:
1 parent
708c08259b
commit
0b18dc018a
8 files changed
+434
-35
No files matched your search
+205
-23
@@ -1,5 +1,5 @@
|
||||
import { Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
||||
import { GPX_ICON, NEW_FOLDER_ICON, UPLOAD_ICON, WAYPOINT_ICON, TRACK_ICON, ROUTE_ICON } from "/js/icons.js";
|
||||
import { GPX_ICON, NEW_FOLDER_ICON, UPLOAD_ICON, WAYPOINT_ICON, TRACK_ICON, ROUTE_ICON, POI_ICONS } from "/js/icons.js";
|
||||
import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
|
||||
import { formatActivityType } from "/js/track_profile.js";
|
||||
|
||||
@@ -8,6 +8,9 @@ const UPLOAD_URL = "/api/gpx";
|
||||
const FOLDER_URL = "/api/gpx/folder";
|
||||
const MOVE_URL = "/api/gpx/move";
|
||||
const TRACK_COLOR = "#e63946";
|
||||
const POI_ICON_KEYS = Object.keys(POI_ICONS);
|
||||
const POI_ICON_IMAGE_SIZE = 48; // rasterized once at this size, rendered much smaller by icon-size below
|
||||
const POI_ICON_SIZE = 0.3; // 48 * 0.3 = ~14px, matching the unclustered circle's 14px diameter
|
||||
|
||||
// Custom drag payload MIME type for moving an already-uploaded file between
|
||||
// folders, as opposed to an OS file drag (type "Files") for uploading a new
|
||||
@@ -24,14 +27,33 @@ export class GpxPanelControl {
|
||||
this._profilePanel = profilePanel;
|
||||
this._visible = new Set(); // file paths currently shown on the map
|
||||
this._interactiveLayers = new Set(); // point layer ids with click/hover wired up
|
||||
this._pointsByPath = new Map(); // path -> its waypoints FeatureCollection, for the category legend
|
||||
|
||||
// setStyle() (switching the Online/Offline base map) tears down all
|
||||
// custom sources and layers — put visible GPX layers back afterwards.
|
||||
// custom sources/layers/images — re-register the POI icon sprites
|
||||
// before putting visible GPX layers back, so a symbol layer added right
|
||||
// away doesn't reference a not-yet-existing image.
|
||||
this._iconsReady = this._registerPoiIcons();
|
||||
map.on("style.load", () => {
|
||||
this._iconsReady = this._registerPoiIcons();
|
||||
this._visible.forEach((path) => this._addLayers(path));
|
||||
});
|
||||
}
|
||||
|
||||
// SDF images (a single alpha shape, tinted at render time via icon-color)
|
||||
// rather than plain color images: the source SVGs are silhouettes with no
|
||||
// color information worth preserving, and SDF lets the same sprite be
|
||||
// reused if a future category needs a different tint.
|
||||
async _registerPoiIcons() {
|
||||
await Promise.all(
|
||||
POI_ICON_KEYS.map(async (key) => {
|
||||
if (this._map.hasImage(key)) return;
|
||||
const imageData = await svgToImageData(POI_ICONS[key], POI_ICON_IMAGE_SIZE);
|
||||
if (!this._map.hasImage(key)) this._map.addImage(key, imageData, { sdf: true });
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
mount(sidebar) {
|
||||
this._container = document.createElement("div");
|
||||
this._container.className = "sidebar-item";
|
||||
@@ -41,6 +63,7 @@ export class GpxPanelControl {
|
||||
|
||||
this._panel = document.getElementById("gpx-panel");
|
||||
this._treeContainer = this._panel.querySelector(".gpx-tree");
|
||||
this._legendContainer = this._panel.querySelector(".gpx-legend");
|
||||
this._uploadStatus = this._panel.querySelector(".gpx-upload__status");
|
||||
this._panel.querySelector('[data-action="new-folder"]').innerHTML = NEW_FOLDER_ICON;
|
||||
this._panel.querySelector('[data-action="upload"]').innerHTML = UPLOAD_ICON;
|
||||
@@ -294,8 +317,9 @@ export class GpxPanelControl {
|
||||
// instead of the layer just silently never appearing. Returns whether it
|
||||
// succeeded.
|
||||
async _addLayers(path) {
|
||||
const id = sourceId(path);
|
||||
if (this._map.getSource(id)) return true;
|
||||
const linesId = linesSourceId(path);
|
||||
const pointsId = pointsSourceId(path);
|
||||
if (this._map.getSource(linesId) || this._map.getSource(pointsId)) return true;
|
||||
|
||||
let geojson;
|
||||
try {
|
||||
@@ -311,33 +335,120 @@ export class GpxPanelControl {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this._map.getSource(id)) return true; // added concurrently (e.g. a style.load race) while this was fetching
|
||||
if (this._map.getSource(linesId) || this._map.getSource(pointsId)) return true; // added concurrently (e.g. a style.load race) while this was fetching
|
||||
|
||||
this._map.addSource(id, { type: "geojson", data: geojson });
|
||||
// Split into two sources: MapLibre's clustering only understands a
|
||||
// source made entirely of Point/MultiPoint features, and a file can mix
|
||||
// a track/route line with waypoints (or, like a park4night POI export,
|
||||
// be thousands of waypoints and nothing else).
|
||||
const lines = { type: "FeatureCollection", features: [] };
|
||||
const points = { type: "FeatureCollection", features: [] };
|
||||
for (const feature of geojson.features) {
|
||||
(feature.geometry.type === "Point" ? points : lines).features.push(feature);
|
||||
}
|
||||
|
||||
this._map.addSource(linesId, { type: "geojson", data: lines });
|
||||
this._map.addLayer({
|
||||
id: `${id}-line`,
|
||||
id: `${linesId}-line`,
|
||||
type: "line",
|
||||
source: id,
|
||||
filter: ["==", ["geometry-type"], "LineString"],
|
||||
source: linesId,
|
||||
layout: { "line-cap": "round", "line-join": "round" },
|
||||
paint: { "line-color": TRACK_COLOR, "line-width": 3 },
|
||||
});
|
||||
this._registerLineInteractivity(`${linesId}-line`);
|
||||
|
||||
// clusterRadius/clusterMaxZoom are harmless when there's nothing dense
|
||||
// enough to cluster (a handful of waypoints just render individually).
|
||||
this._map.addSource(pointsId, { type: "geojson", data: points, cluster: true, clusterRadius: 50, clusterMaxZoom: 14 });
|
||||
await this._iconsReady;
|
||||
if (!this._map.getSource(pointsId)) return true; // a style.load (basemap switch) tore it down while icons were loading
|
||||
|
||||
this._addClusterLayers(pointsId);
|
||||
|
||||
if (points.features.length > 0) this._pointsByPath.set(path, points);
|
||||
this._updateLegend();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// A single-hue, light->dark ramp keyed on point_count (magnitude, not
|
||||
// category) for the clustered circles; individual points below that use
|
||||
// each waypoint's own category color (see Maptool::Gpx#waypoint_color),
|
||||
// falling back to the plain track color for waypoints with no category
|
||||
// (e.g. a hand-placed GNSS pin, not from a POI export).
|
||||
_addClusterLayers(pointsId) {
|
||||
this._map.addLayer({
|
||||
id: `${id}-points`,
|
||||
id: `${pointsId}-clusters`,
|
||||
type: "circle",
|
||||
source: id,
|
||||
filter: ["==", ["geometry-type"], "Point"],
|
||||
source: pointsId,
|
||||
filter: ["has", "point_count"],
|
||||
paint: {
|
||||
"circle-radius": 5,
|
||||
"circle-color": TRACK_COLOR,
|
||||
"circle-radius": ["step", ["get", "point_count"], 16, 25, 20, 100, 26],
|
||||
"circle-color": ["step", ["get", "point_count"], "#a8c8ea", 25, "#5b9bd5", 100, "#2e6da4"],
|
||||
"circle-stroke-color": "#fff",
|
||||
"circle-stroke-width": 1.5,
|
||||
},
|
||||
});
|
||||
this._map.addLayer({
|
||||
id: `${pointsId}-cluster-count`,
|
||||
type: "symbol",
|
||||
source: pointsId,
|
||||
filter: ["has", "point_count"],
|
||||
layout: { "text-field": ["get", "point_count_abbreviated"], "text-font": ["Noto Sans Regular"], "text-size": 11 },
|
||||
paint: { "text-color": "#fff" },
|
||||
});
|
||||
this._map.addLayer({
|
||||
id: `${pointsId}-unclustered`,
|
||||
type: "circle",
|
||||
source: pointsId,
|
||||
filter: ["!", ["has", "point_count"]],
|
||||
paint: {
|
||||
"circle-radius": 7,
|
||||
"circle-color": ["coalesce", ["get", "color"], TRACK_COLOR],
|
||||
"circle-stroke-color": "#fff",
|
||||
"circle-stroke-width": 1.5,
|
||||
},
|
||||
});
|
||||
// Only for the curated POI_ICON_KEYS (see icons.js) — anything else
|
||||
// (a plain hand-placed waypoint, or a category p4n2gpx/OsmAnd hasn't
|
||||
// been taught here) just keeps the colored dot above with no icon.
|
||||
this._map.addLayer({
|
||||
id: `${pointsId}-unclustered-icon`,
|
||||
type: "symbol",
|
||||
source: pointsId,
|
||||
filter: ["all", ["!", ["has", "point_count"]], ["in", ["get", "icon"], ["literal", POI_ICON_KEYS]]],
|
||||
layout: {
|
||||
"icon-image": ["get", "icon"],
|
||||
"icon-size": POI_ICON_SIZE,
|
||||
"icon-allow-overlap": true,
|
||||
"icon-ignore-placement": true,
|
||||
},
|
||||
paint: { "icon-color": "#fff" },
|
||||
});
|
||||
|
||||
this._registerPointInteractivity(`${id}-points`);
|
||||
this._registerLineInteractivity(`${id}-line`);
|
||||
return true;
|
||||
this._registerClusterInteractivity(pointsId);
|
||||
this._registerPointInteractivity(`${pointsId}-unclustered`);
|
||||
}
|
||||
|
||||
// Clicking a cluster zooms in just far enough to break it apart, the
|
||||
// standard MapLibre cluster-expansion pattern.
|
||||
_registerClusterInteractivity(pointsId) {
|
||||
const clusterId = `${pointsId}-clusters`;
|
||||
if (this._interactiveLayers.has(clusterId)) return;
|
||||
this._interactiveLayers.add(clusterId);
|
||||
|
||||
this._map.on("click", clusterId, async (event) => {
|
||||
const feature = this._map.queryRenderedFeatures(event.point, { layers: [clusterId] })[0];
|
||||
if (!feature) return;
|
||||
const zoom = await this._map.getSource(pointsId).getClusterExpansionZoom(feature.properties.cluster_id);
|
||||
this._map.easeTo({ center: feature.geometry.coordinates, zoom });
|
||||
});
|
||||
this._map.on("mouseenter", clusterId, () => {
|
||||
this._map.getCanvas().style.cursor = "pointer";
|
||||
});
|
||||
this._map.on("mouseleave", clusterId, () => {
|
||||
this._map.getCanvas().style.cursor = "";
|
||||
});
|
||||
}
|
||||
|
||||
// Registered once per layer id, ever — map.on(type, layerId, fn) is a
|
||||
@@ -396,11 +507,50 @@ export class GpxPanelControl {
|
||||
}
|
||||
|
||||
_removeLayers(path) {
|
||||
const id = sourceId(path);
|
||||
[`${id}-line`, `${id}-points`].forEach((layerId) => {
|
||||
const linesId = linesSourceId(path);
|
||||
const pointsId = pointsSourceId(path);
|
||||
[
|
||||
`${linesId}-line`,
|
||||
`${pointsId}-clusters`,
|
||||
`${pointsId}-cluster-count`,
|
||||
`${pointsId}-unclustered`,
|
||||
`${pointsId}-unclustered-icon`,
|
||||
].forEach((layerId) => {
|
||||
if (this._map.getLayer(layerId)) this._map.removeLayer(layerId);
|
||||
});
|
||||
if (this._map.getSource(id)) this._map.removeSource(id);
|
||||
if (this._map.getSource(linesId)) this._map.removeSource(linesId);
|
||||
if (this._map.getSource(pointsId)) this._map.removeSource(pointsId);
|
||||
|
||||
this._pointsByPath.delete(path);
|
||||
this._updateLegend();
|
||||
}
|
||||
|
||||
// Rebuilt from whichever visible files actually carry categorized
|
||||
// waypoints (a park4night/OsmAnd POI export) — a plain GPS track has none
|
||||
// and the legend just stays hidden.
|
||||
_updateLegend() {
|
||||
const categories = new Map(); // category name -> color
|
||||
for (const points of this._pointsByPath.values()) {
|
||||
for (const feature of points.features) {
|
||||
const category = feature.properties.category;
|
||||
if (category && !categories.has(category)) categories.set(category, feature.properties.color || TRACK_COLOR);
|
||||
}
|
||||
}
|
||||
|
||||
this._legendContainer.innerHTML = "";
|
||||
this._legendContainer.hidden = categories.size === 0;
|
||||
[...categories].sort(([a], [b]) => a.localeCompare(b)).forEach(([category, color]) => {
|
||||
const item = document.createElement("div");
|
||||
item.className = "gpx-legend__item";
|
||||
const swatch = document.createElement("span");
|
||||
swatch.className = "gpx-legend__swatch";
|
||||
swatch.style.background = color; // a malformed/malicious value from an uploaded file is simply ignored by the CSSOM, never parsed as markup
|
||||
const label = document.createElement("span");
|
||||
label.textContent = category;
|
||||
item.appendChild(swatch);
|
||||
item.appendChild(label);
|
||||
this._legendContainer.appendChild(item);
|
||||
});
|
||||
}
|
||||
|
||||
async _uploadFiles(fileList, folder) {
|
||||
@@ -504,8 +654,39 @@ function redirectIfUnauthorized(response) {
|
||||
return true;
|
||||
}
|
||||
|
||||
function sourceId(path) {
|
||||
return `gpx-${path}`;
|
||||
// Rasterizes a hand-authored SVG icon to ImageData for map.addImage(), at a
|
||||
// fixed square size (the source SVGs have no explicit width/height, just a
|
||||
// viewBox, so one is injected — otherwise an <img> falls back to the CSS
|
||||
// default replaced-element size instead of the viewBox's aspect).
|
||||
async function svgToImageData(svgMarkup, size) {
|
||||
// xmlns is required here even though the other hand-drawn icons in this
|
||||
// app get away without it — those are inlined via innerHTML, where the
|
||||
// HTML parser assigns the SVG namespace from context, but a standalone
|
||||
// <img src="blob:..."> loads it as its own XML document, which needs an
|
||||
// explicit namespace or every browser refuses to decode it.
|
||||
const sized = svgMarkup.replace("<svg ", `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" `);
|
||||
const url = URL.createObjectURL(new Blob([sized], { type: "image/svg+xml" }));
|
||||
try {
|
||||
const img = new Image();
|
||||
img.src = url;
|
||||
await img.decode();
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = size;
|
||||
canvas.height = size;
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx.drawImage(img, 0, 0, size, size);
|
||||
return ctx.getImageData(0, 0, size, size);
|
||||
} finally {
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
}
|
||||
|
||||
function linesSourceId(path) {
|
||||
return `gpx-${path}-lines`;
|
||||
}
|
||||
|
||||
function pointsSourceId(path) {
|
||||
return `gpx-${path}-points`;
|
||||
}
|
||||
|
||||
function gpxFileUrl(path) {
|
||||
@@ -514,9 +695,10 @@ function gpxFileUrl(path) {
|
||||
|
||||
// properties come straight from an uploaded GPX file — untrusted input —
|
||||
// so every value is escaped before landing in the popup's HTML.
|
||||
function popupHtml({ name, description, time }) {
|
||||
function popupHtml({ name, description, time, category }) {
|
||||
const parts = [];
|
||||
if (name) parts.push(`<strong>${escapeHtml(name)}</strong>`);
|
||||
if (category) parts.push(`<p class="gpx-popup__category">${escapeHtml(category)}</p>`);
|
||||
if (description) parts.push(`<p>${linkify(description).replace(/\n/g, "<br>")}</p>`);
|
||||
if (time) {
|
||||
const parsed = new Date(time);
|
||||
|
||||
@@ -58,6 +58,53 @@ export const ROUTE_ICON = `
|
||||
<path d="M6.5 7.5C10 11 8 13 12 13s2 5 6.5 5" stroke-dasharray="2 2.2"/>
|
||||
</svg>`;
|
||||
|
||||
// POI category glyphs (park4night/OsmAnd exports), keyed by the OsmAnd icon
|
||||
// name a file's <osmand:icon> extension carries — a small curated set for
|
||||
// the categories park4night actually uses (see waypoint_style in
|
||||
// lib/maptool/gpx.rb), not an exhaustive OsmAnd icon set. Filled shapes
|
||||
// (not stroked outlines like the sidebar icons above) since these render at
|
||||
// ~14px on the map, where a hairline stroke disappears; solid silhouettes
|
||||
// stay legible that small. Rasterized and used as SDF map icons (see
|
||||
// gpx.js), so only the alpha shape matters — the actual `currentColor`
|
||||
// value is irrelevant.
|
||||
export const POI_ICONS = {
|
||||
amenity_parking: `
|
||||
<svg viewBox="0 0 24 24"><text x="12" y="18" font-family="Arial, Helvetica, sans-serif" font-size="16" font-weight="700" text-anchor="middle" fill="currentColor">P</text></svg>`,
|
||||
|
||||
tourism_camp_site: `
|
||||
<svg viewBox="0 0 24 24"><path fill-rule="evenodd" clip-rule="evenodd" d="M12 3 22 20 2 20 Z M12 12 15.5 20 8.5 20 Z" fill="currentColor"/></svg>`,
|
||||
|
||||
leisure_picnic_table: `
|
||||
<svg viewBox="0 0 24 24">
|
||||
<rect x="3" y="9" width="18" height="3" fill="currentColor"/>
|
||||
<path d="M5 12 2 20 5 20 7.5 12 Z M19 12 22 20 19 20 16.5 12 Z" fill="currentColor"/>
|
||||
</svg>`,
|
||||
|
||||
amenity_fuel: `
|
||||
<svg viewBox="0 0 24 24"><path d="M12 2C12 2 5 11 5 15.5A7 7 0 0 0 19 15.5C19 11 12 2 12 2Z" fill="currentColor"/></svg>`,
|
||||
|
||||
tourism_hotel: `
|
||||
<svg viewBox="0 0 24 24">
|
||||
<rect x="3" y="11" width="18" height="7" rx="1.5" fill="currentColor"/>
|
||||
<rect x="4" y="8" width="6" height="4" rx="1" fill="currentColor"/>
|
||||
<rect x="3" y="18" width="2" height="3" fill="currentColor"/>
|
||||
<rect x="19" y="18" width="2" height="3" fill="currentColor"/>
|
||||
</svg>`,
|
||||
|
||||
forest: `
|
||||
<svg viewBox="0 0 24 24">
|
||||
<path d="M12 2 18 12 15 12 19 19 5 19 9 12 6 12Z" fill="currentColor"/>
|
||||
<rect x="10.5" y="19" width="3" height="3" fill="currentColor"/>
|
||||
</svg>`,
|
||||
|
||||
sport_cycling: `
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="6" cy="17" r="4"/>
|
||||
<circle cx="18" cy="17" r="4"/>
|
||||
<path d="M6 17 11 8H15M11 8 15 17M18 17 14 10"/>
|
||||
</svg>`,
|
||||
};
|
||||
|
||||
export const LIVETRACK_ICON = `
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M12 21s7-7.58 7-12a7 7 0 0 0-14 0c0 4.42 7 12 7 12z"/>
|
||||
|
||||
Reference in new issue
Block a user