Files
gpx.studio/website/src/lib/components/map/layer-control/overpass-layer.ts
T

302 lines
11 KiB
TypeScript
Raw Normal View History

2025-06-08 16:32:41 +02:00
import { SphericalMercator } from '@mapbox/sphericalmercator';
2025-10-17 23:54:45 +02:00
import { getLayers } from './utils';
2025-02-02 11:17:22 +01:00
import { get, writable } from 'svelte/store';
2026-10-11 11:18:36 +02:00
import { overpassQueryData } from '$lib/data/layers';
2025-10-17 23:54:45 +02:00
import { MapPopup } from '$lib/components/map/map-popup';
2026-10-11 11:18:36 +02:00
import { settings } from '$lib/state/settings';
2026-10-18 18:15:37 +02:00
import type { GeoJSONSource, Map as MapLibreMap } from 'maplibre-gl';
2026-03-27 18:31:23 +01:00
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
import type { MapLayerEventManager } from '$lib/components/map/map-layer-event-manager';
2026-02-01 17:18:17 +01:00
import { loadSVGIcon } from '$lib/utils';
2026-10-11 11:18:36 +02:00
import { cachedFetch } from '$lib/storage/cached-fetch';
2024-07-16 23:57:17 +02:00
2025-10-17 23:54:45 +02:00
const { currentOverpassQueries } = settings;
2024-07-16 23:57:17 +02:00
2026-10-08 18:34:19 +02:00
/** The responses of Overpass are kept in the browser for a week. */
const CACHE = { name: 'overpass', maxAge: 7 * 24 * 3600 * 1000 };
2024-07-16 23:57:17 +02:00
const mercator = new SphericalMercator({
size: 256,
});
export class OverpassLayer {
2026-05-31 15:25:10 +02:00
overpassUrl = 'https://overpass.gpx.studio/api/interpreter';
2024-07-16 23:57:17 +02:00
minZoom = 12;
2024-07-17 14:19:04 +02:00
queryZoom = 12;
2026-07-24 19:06:39 +02:00
map: MapLibreMap;
layerEventManager: MapLayerEventManager;
popup: MapPopup;
2024-07-16 23:57:17 +02:00
2026-10-08 18:34:19 +02:00
data = writable<GeoJSON.FeatureCollection>({ type: 'FeatureCollection', features: [] });
// What was queried this session: the queries that were made for each tile. The responses are
// kept longer, see `cachedFetch`.
queriedTiles = new Map<string, Set<string>>();
2024-07-16 23:57:17 +02:00
currentQueries: Set<string> = new Set();
unsubscribes: (() => void)[] = [];
queryIfNeededBinded = this.queryIfNeeded.bind(this);
updateBinded = this.update.bind(this);
2024-07-17 19:40:53 +02:00
onHoverBinded = this.onHover.bind(this);
2024-07-16 23:57:17 +02:00
2026-07-24 19:06:39 +02:00
constructor(map: MapLibreMap, layerEventManager: MapLayerEventManager) {
2024-07-16 23:57:17 +02:00
this.map = map;
this.layerEventManager = layerEventManager;
this.popup = new MapPopup(map, {
closeButton: false,
focusAfterOpen: false,
maxWidth: undefined,
offset: 15,
});
2024-07-16 23:57:17 +02:00
}
add() {
this.map.on('moveend', this.queryIfNeededBinded);
2026-01-30 21:01:24 +01:00
this.map.on('style.load', this.updateBinded);
2026-10-08 18:34:19 +02:00
this.unsubscribes.push(this.data.subscribe(this.updateBinded));
2025-02-02 11:17:22 +01:00
this.unsubscribes.push(
currentOverpassQueries.subscribe(() => {
this.updateBinded();
this.queryIfNeededBinded();
})
);
2024-07-16 23:57:17 +02:00
this.update();
}
queryIfNeeded() {
if (this.map.getZoom() >= this.minZoom) {
2025-10-17 23:54:45 +02:00
const bounds = this.map.getBounds()?.toArray();
if (bounds) {
this.query([bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1]]);
}
2024-07-16 23:57:17 +02:00
}
}
update() {
2024-07-17 14:19:04 +02:00
this.loadIcons();
2026-10-08 18:34:19 +02:00
const fullData = get(this.data);
2026-02-01 15:57:18 +01:00
const queries = getCurrentQueries();
const d: GeoJSON.FeatureCollection = {
type: 'FeatureCollection',
features: fullData.features.filter((feature) =>
queries.includes(feature.properties!.query)
),
};
2024-07-16 23:57:17 +02:00
try {
2026-01-30 21:01:24 +01:00
let source = this.map.getSource('overpass') as GeoJSONSource | undefined;
2024-07-16 23:57:17 +02:00
if (source) {
source.setData(d);
} else {
this.map.addSource('overpass', {
type: 'geojson',
data: d,
});
}
if (!this.map.getLayer('overpass')) {
2026-01-30 21:30:37 +01:00
this.map.addLayer(
{
id: 'overpass',
type: 'symbol',
source: 'overpass',
layout: {
'icon-image': ['get', 'icon'],
'icon-size': 0.25,
'icon-padding': 0,
'icon-allow-overlap': ['step', ['zoom'], false, 14, true],
},
2024-07-16 23:57:17 +02:00
},
2026-01-30 21:30:37 +01:00
ANCHOR_LAYER_KEY.overpass
);
2024-07-17 19:40:53 +02:00
this.layerEventManager.on('mouseenter', 'overpass', this.onHoverBinded);
this.layerEventManager.on('click', 'overpass', this.onHoverBinded);
2024-07-16 23:57:17 +02:00
}
} catch (e) {
// No reliable way to check if the map is ready to add sources and layers
}
}
remove() {
this.map.off('moveend', this.queryIfNeededBinded);
2026-01-30 21:01:24 +01:00
this.map.off('style.load', this.updateBinded);
this.layerEventManager.off('mouseenter', 'overpass', this.onHoverBinded);
this.layerEventManager.off('click', 'overpass', this.onHoverBinded);
2024-07-16 23:57:17 +02:00
this.unsubscribes.forEach((unsubscribe) => unsubscribe());
try {
if (this.map.getLayer('overpass')) {
this.map.removeLayer('overpass');
}
2024-07-16 23:57:17 +02:00
if (this.map.getSource('overpass')) {
this.map.removeSource('overpass');
}
} catch (e) {
// No reliable way to check if the map is ready to remove sources and layers
2024-07-16 23:57:17 +02:00
}
}
2024-07-17 19:40:53 +02:00
onHover(e: any) {
this.popup.setItem({
2026-10-04 17:09:41 +02:00
kind: 'overpass',
item: {
...e.features[0].properties,
2025-02-02 11:17:22 +01:00
sym: overpassQueryData[e.features[0].properties.query].symbol ?? '',
},
2024-08-08 17:52:11 +02:00
});
2024-07-17 19:40:53 +02:00
}
2024-07-16 23:57:17 +02:00
query(bbox: [number, number, number, number]) {
2024-07-17 14:19:04 +02:00
let queries = getCurrentQueries();
if (queries.length === 0) {
return;
}
2024-07-16 23:57:17 +02:00
let tileLimits = mercator.xyz(bbox, this.queryZoom);
for (let x = tileLimits.minX; x <= tileLimits.maxX; x++) {
for (let y = tileLimits.minY; y <= tileLimits.maxY; y++) {
if (this.currentQueries.has(`${x},${y}`)) {
continue;
}
2026-10-08 18:34:19 +02:00
const queried = this.queriedTiles.get(`${x},${y}`);
const missingQueries = queries.filter((query) => !queried?.has(query));
if (missingQueries.length > 0) {
this.queryTile(x, y, missingQueries);
}
2024-07-16 23:57:17 +02:00
}
}
}
2024-07-17 14:19:04 +02:00
queryTile(x: number, y: number, queries: string[]) {
2024-07-16 23:57:17 +02:00
this.currentQueries.add(`${x},${y}`);
const bounds = mercator.bbox(x, y, this.queryZoom);
2026-10-08 18:34:19 +02:00
cachedFetch(`${this.overpassUrl}?data=${getQueryForBounds(bounds, queries)}`, CACHE)
.then((response) => (response.ok ? response.json() : Promise.reject()))
2024-07-17 23:05:17 +02:00
.then((data) => this.storeOverpassData(x, y, queries, data))
.catch(() => this.currentQueries.delete(`${x},${y}`));
2024-07-16 23:57:17 +02:00
}
2024-07-17 14:19:04 +02:00
storeOverpassData(x: number, y: number, queries: string[], data: any) {
2024-07-17 19:40:53 +02:00
if (data.elements === undefined) {
return;
}
2026-10-08 18:34:19 +02:00
this.data.update((updatedData) => {
for (let element of data.elements) {
for (let query of queries) {
if (belongsToQuery(element, query)) {
updatedData.features.push({
2024-07-16 23:57:17 +02:00
type: 'Feature',
geometry: {
type: 'Point',
2025-02-02 11:17:22 +01:00
coordinates: element.center
? [element.center.lon, element.center.lat]
: [element.lon, element.lat],
2024-07-17 19:40:53 +02:00
},
properties: {
id: element.id,
lat: element.center ? element.center.lat : element.lat,
2026-10-04 17:09:41 +02:00
lng: element.center ? element.center.lon : element.lon,
2024-07-17 19:40:53 +02:00
query: query,
icon: `overpass-${query}`,
2025-02-02 11:17:22 +01:00
tags: element.tags,
2025-04-11 18:40:16 +02:00
type: element.type,
2024-07-16 23:57:17 +02:00
},
2026-10-08 18:34:19 +02:00
});
}
2024-07-16 23:57:17 +02:00
}
}
2026-10-08 18:34:19 +02:00
return updatedData;
2024-07-16 23:57:17 +02:00
});
2026-10-08 18:34:19 +02:00
const queried = this.queriedTiles.get(`${x},${y}`) ?? new Set<string>();
queries.forEach((query) => queried.add(query));
this.queriedTiles.set(`${x},${y}`, queried);
2024-07-16 23:57:17 +02:00
this.currentQueries.delete(`${x},${y}`);
}
2024-07-17 14:19:04 +02:00
loadIcons() {
let currentQueries = getCurrentQueries();
currentQueries.forEach((query) => {
2026-02-01 17:18:17 +01:00
loadSVGIcon(
this.map,
`overpass-${query}`,
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">
2024-07-17 19:40:53 +02:00
<circle cx="20" cy="20" r="20" fill="${overpassQueryData[query].icon.color}" />
2024-07-17 14:19:04 +02:00
<g transform="translate(8 8)">
2024-07-17 19:40:53 +02:00
${overpassQueryData[query].icon.svg.replace('stroke="currentColor"', 'stroke="white"')}
2024-07-17 14:19:04 +02:00
</g>
2026-02-01 17:18:17 +01:00
</svg>`
);
2024-07-17 14:19:04 +02:00
});
}
2024-07-16 23:57:17 +02:00
}
2024-07-17 14:19:04 +02:00
function getQueryForBounds(bounds: [number, number, number, number], queries: string[]) {
2024-07-17 19:40:53 +02:00
return `[bbox:${bounds[1]},${bounds[0]},${bounds[3]},${bounds[2]}][out:json];(${getQueries(queries)});out center;`;
2024-07-16 23:57:17 +02:00
}
2024-07-17 14:19:04 +02:00
function getQueries(queries: string[]) {
2024-07-17 19:40:53 +02:00
return queries.map((query) => getQuery(query)).join('');
2024-07-16 23:57:17 +02:00
}
2024-07-17 14:19:04 +02:00
function getQuery(query: string) {
if (Array.isArray(overpassQueryData[query].tags)) {
return overpassQueryData[query].tags.map((tags) => getQueryItem(tags)).join('');
} else {
return getQueryItem(overpassQueryData[query].tags);
}
}
function getQueryItem(tags: Record<string, string | string[]>) {
let arrayEntry = Object.entries(tags).find((entry): entry is [string, string[]] =>
Array.isArray(entry[1])
);
2024-07-17 19:40:53 +02:00
if (arrayEntry !== undefined) {
return arrayEntry[1]
2025-02-02 11:17:22 +01:00
.map(
(val) =>
`nwr${Object.entries(tags)
.map(([tag, value]) => `[${tag}=${tag === arrayEntry[0] ? val : value}]`)
.join('')};`
)
.join('');
2024-07-17 19:40:53 +02:00
} else {
return `nwr${Object.entries(tags)
2024-07-17 19:40:53 +02:00
.map(([tag, value]) => `[${tag}=${value}]`)
.join('')};`;
}
2024-07-16 23:57:17 +02:00
}
2024-07-17 14:19:04 +02:00
function belongsToQuery(element: any, query: string) {
if (Array.isArray(overpassQueryData[query].tags)) {
return overpassQueryData[query].tags.some((tags) => belongsToQueryItem(element, tags));
} else {
return belongsToQueryItem(element, overpassQueryData[query].tags);
}
}
function belongsToQueryItem(element: any, tags: Record<string, string | string[]>) {
2025-02-02 11:17:22 +01:00
return Object.entries(tags).every(([tag, value]) =>
Array.isArray(value) ? value.includes(element.tags[tag]) : element.tags[tag] === value
);
2024-07-17 14:19:04 +02:00
}
function getCurrentQueries() {
let currentQueries = get(currentOverpassQueries);
if (currentQueries === undefined) {
return [];
}
2025-02-02 11:17:22 +01:00
return Object.entries(getLayers(currentQueries))
.filter(([_, selected]) => selected)
.map(([query, _]) => query);
}