26 Commits

Author SHA1 Message Date
vcoppe
b8c1500aad fix layer filtering in event manager 2026-02-02 21:50:01 +01:00
vcoppe
bfd0d90abc validate settings 2026-02-01 18:45:40 +01:00
vcoppe
dba01e1826 finish renaming 2026-02-01 18:06:16 +01:00
vcoppe
2189c76edd renaming 2026-02-01 17:46:24 +01:00
vcoppe
6f8c9d66db use map layers for start/end/hover markers 2026-02-01 17:18:17 +01:00
vcoppe
9408ce10c7 check that map contains the layer 2026-02-01 16:26:17 +01:00
vcoppe
9895c3c304 further improve event listener performance 2026-02-01 15:57:18 +01:00
vcoppe
0ab3b77db8 centralized map layer event listener for better performance 2026-01-31 12:57:08 +01:00
vcoppe
d13e7e7a0a update package-lock 2026-01-30 23:13:02 +01:00
vcoppe
e96b544a75 switch to maplibre, but laggy 2026-01-30 21:01:24 +01:00
vcoppe
375204c379 New Crowdin updates (#304)
* New translations en.json (Dutch)

* New translations en.json (Czech)

* New translations en.json (Spanish)

* New translations file.mdx (Vietnamese)

* New translations en.json (Polish)
2026-01-28 17:54:01 +01:00
vcoppe
d76c03af4f add try catch to setTerrain 2026-01-28 17:53:26 +01:00
vcoppe
200a6586ba remove unused glyphs url with empty key causing problems 2026-01-28 17:53:12 +01:00
vcoppe
f0f1ecb2df New Crowdin updates (#303)
* New translations en.json (Spanish)

* New translations en.json (German)

* New translations en.json (Romanian)

* New translations en.json (French)

* New translations en.json (Belarusian)

* New translations en.json (Catalan)

* New translations en.json (Czech)

* New translations en.json (Danish)

* New translations en.json (Greek)

* New translations en.json (Basque)

* New translations en.json (Finnish)

* New translations en.json (Hebrew)

* New translations en.json (Chinese Simplified)

* New translations en.json (Polish)

* New translations en.json (Italian)

* New translations en.json (Hungarian)

* New translations en.json (Korean)

* New translations en.json (Lithuanian)

* New translations en.json (Dutch)

* New translations en.json (Norwegian)

* New translations en.json (Portuguese)

* New translations en.json (Russian)

* New translations en.json (Swedish)

* New translations en.json (Turkish)

* New translations en.json (Ukrainian)

* New translations en.json (Vietnamese)

* New translations en.json (Portuguese, Brazilian)

* New translations en.json (Indonesian)

* New translations en.json (Thai)

* New translations en.json (Latvian)

* New translations en.json (Chinese Traditional, Hong Kong)

* New translations en.json (Serbian (Latin))

* New translations mapbox.mdx (German)

* New translations en.json (Chinese Simplified)

* New translations en.json (Polish)

* New translations en.json (Spanish)

* New translations en.json (German)

* New translations en.json (Italian)

* New translations en.json (Romanian)

* New translations en.json (French)

* New translations en.json (Belarusian)

* New translations en.json (Catalan)

* New translations en.json (Czech)

* New translations en.json (Danish)

* New translations en.json (Greek)

* New translations en.json (Basque)

* New translations en.json (Finnish)

* New translations en.json (Hebrew)

* New translations en.json (Hungarian)

* New translations en.json (Korean)

* New translations en.json (Lithuanian)

* New translations en.json (Dutch)

* New translations en.json (Norwegian)

* New translations en.json (Portuguese)

* New translations en.json (Russian)

* New translations en.json (Swedish)

* New translations en.json (Turkish)

* New translations en.json (Ukrainian)

* New translations en.json (Vietnamese)

* New translations en.json (Portuguese, Brazilian)

* New translations en.json (Indonesian)

* New translations en.json (Thai)

* New translations en.json (Latvian)

* New translations en.json (Chinese Traditional, Hong Kong)

* New translations en.json (Serbian (Latin))

* New translations en.json (French)
2026-01-16 20:06:44 +01:00
vcoppe
2eb6ef6f03 new setting for selecting terrain source 2026-01-16 19:16:28 +01:00
vcoppe
f7c0805161 add mapterhorn hillshade overlay, closes #292 2026-01-16 18:32:32 +01:00
vcoppe
4e18e3c8a0 update year 2026-01-16 18:25:27 +01:00
vcoppe
59f31caf26 add openrailwaymap overlay, closes #298 2026-01-11 20:18:00 +01:00
vcoppe
f24956c58d improve grouping statistics performance 2026-01-11 19:48:48 +01:00
vcoppe
9019317e5c fix prettier paths, continued 2026-01-11 19:06:54 +01:00
vcoppe
2a0227c1de New Crowdin updates (#300)
* New translations en.json (Spanish)

* New translations en.json (German)

* New translations en.json (Italian)

* New translations files-and-stats.mdx (Italian)

* New translations gpx.mdx (Italian)

* New translations funding.mdx (Italian)

* New translations en.json (French)
2026-01-11 11:09:41 +01:00
vcoppe
f70db42b91 New Crowdin updates (#294)
* New translations en.json (Vietnamese)

* New translations en.json (Vietnamese)

* New translations funding.mdx (Vietnamese)

* New translations mapbox.mdx (Vietnamese)

* New translations edit.mdx (Vietnamese)

* New translations file.mdx (Chinese Simplified)

* New translations en.json (Chinese Simplified)

* New translations en.json (Polish)
2026-01-04 21:39:32 +01:00
vcoppe
9cd87742f0 avoid performing a get on unit stores for each point 2026-01-04 19:52:25 +01:00
vcoppe
5dcb93ca5d fix loading style font 2026-01-04 19:29:46 +01:00
vcoppe
256d62b29b only perform layer selection checks when settings are open 2026-01-04 19:00:13 +01:00
vcoppe
595ea8e2d3 revert clone function switch 2025-12-26 14:17:23 +01:00
123 changed files with 2959 additions and 2708 deletions

View File

@@ -31,7 +31,7 @@ jobs:
- name: Create env file - name: Create env file
run: | run: |
touch website/.env touch website/.env
echo PUBLIC_MAPBOX_TOKEN=${{ secrets.PUBLIC_MAPBOX_TOKEN }} >> website/.env echo PUBLIC_MAPTILER_KEY=${{ secrets.PUBLIC_MAPTILER_KEY }} >> website/.env
cat website/.env cat website/.env
- name: Build website - name: Build website

3
.prettierignore Normal file
View File

@@ -0,0 +1,3 @@
website/src/lib/components/ui
website/src/lib/docs/**/*.mdx
**/*.webmanifest

View File

@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2025 gpx.studio Copyright (c) 2026 gpx.studio
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@@ -27,8 +27,8 @@ Any help is greatly appreciated!
The code is split into two parts: The code is split into two parts:
- `gpx`: a Typescript library for parsing and manipulating GPX files, - `gpx`: a Typescript library for parsing and manipulating GPX files,
- `website`: the website itself, which is a [SvelteKit](https://kit.svelte.dev/) application. - `website`: the website itself, which is a [SvelteKit](https://kit.svelte.dev/) application.
You will need [Node.js](https://nodejs.org/) to build and run these two parts. You will need [Node.js](https://nodejs.org/) to build and run these two parts.
@@ -42,11 +42,11 @@ npm run build
### Running the website ### Running the website
To be able to load the map, you will need to create your own <a href="https://account.mapbox.com/auth/signup" target="_blank">Mapbox access token</a> and store it in a `.env` file in the `website` directory. To be able to load the map, you will need to create your own <a href="https://cloud.maptiler.com/auth/widget?next=https://cloud.maptiler.com/maps/" target="_blank">MapTiler key</a> and store it in a `.env` file in the `website` directory.
```bash ```bash
cd website cd website
echo PUBLIC_MAPBOX_TOKEN={YOUR_MAPBOX_TOKEN} >> .env echo PUBLIC_MAPTILER_KEY={YOUR_MAPTILER_KEY} >> .env
npm install npm install
npm run dev npm run dev
``` ```
@@ -55,25 +55,25 @@ npm run dev
This project has been made possible thanks to the following open source projects: This project has been made possible thanks to the following open source projects:
- Development: - Development:
- [Svelte](https://github.com/sveltejs/svelte) and [SvelteKit](https://github.com/sveltejs/kit) — seamless development experience - [Svelte](https://github.com/sveltejs/svelte) and [SvelteKit](https://github.com/sveltejs/kit) — seamless development experience
- [MDsveX](https://github.com/pngwn/MDsveX) — allowing a Markdown-based documentation - [MDsveX](https://github.com/pngwn/MDsveX) — allowing a Markdown-based documentation
- Design: - Design:
- [shadcn-svelte](https://github.com/huntabyte/shadcn-svelte) — beautiful components - [shadcn-svelte](https://github.com/huntabyte/shadcn-svelte) — beautiful components
- [@lucide/svelte](https://github.com/lucide-icons/lucide/tree/main/packages/svelte) — beautiful icons - [@lucide/svelte](https://github.com/lucide-icons/lucide/tree/main/packages/svelte) — beautiful icons
- [tailwindcss](https://github.com/tailwindlabs/tailwindcss) — easy styling - [tailwindcss](https://github.com/tailwindlabs/tailwindcss) — easy styling
- [Chart.js](https://github.com/chartjs/Chart.js) — beautiful and fast charts - [Chart.js](https://github.com/chartjs/Chart.js) — beautiful and fast charts
- Logic: - Logic:
- [immer](https://github.com/immerjs/immer) — complex state management - [immer](https://github.com/immerjs/immer) — complex state management
- [Dexie.js](https://github.com/dexie/Dexie.js) — IndexedDB wrapper - [Dexie.js](https://github.com/dexie/Dexie.js) — IndexedDB wrapper
- [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) — fast GPX file parsing - [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) — fast GPX file parsing
- [SortableJS](https://github.com/SortableJS/Sortable) — creating a sortable file tree - [SortableJS](https://github.com/SortableJS/Sortable) — creating a sortable file tree
- Mapping: - Mapping:
- [Mapbox GL JS](https://github.com/mapbox/mapbox-gl-js) — beautiful and fast interactive maps - [MapLibre GL JS](https://github.com/maplibre/maplibre-gl-js) — beautiful and fast interactive maps
- [brouter](https://github.com/abrensch/brouter) — routing engine - [brouter](https://github.com/abrensch/brouter) — routing engine
- [OpenStreetMap](https://www.openstreetmap.org) — map data used by Mapbox and brouter - [OpenStreetMap](https://www.openstreetmap.org) — map data used by most of the map layers, and by the routing engine
- Search: - Search:
- [DocSearch](https://github.com/algolia/docsearch) — search engine for the documentation - [DocSearch](https://github.com/algolia/docsearch) — search engine for the documentation
## License ## License

View File

@@ -1,4 +1,5 @@
import { ramerDouglasPeucker } from './simplify'; import { ramerDouglasPeucker } from './simplify';
import { GPXStatistics, GPXStatisticsGroup, TrackPointLocalStatistics } from './statistics';
import { import {
Coordinates, Coordinates,
GPXFileAttributes, GPXFileAttributes,
@@ -16,6 +17,16 @@ import {
} from './types'; } from './types';
import { immerable, isDraft, original, freeze } from 'immer'; import { immerable, isDraft, original, freeze } from 'immer';
function cloneJSON<T>(obj: T): T {
if (obj === undefined) {
return undefined;
}
if (obj === null || typeof obj !== 'object') {
return null;
}
return JSON.parse(JSON.stringify(obj));
}
// An abstract class that groups functions that need to be computed recursively in the GPX file hierarchy // An abstract class that groups functions that need to be computed recursively in the GPX file hierarchy
export abstract class GPXTreeElement<T extends GPXTreeElement<any>> { export abstract class GPXTreeElement<T extends GPXTreeElement<any>> {
_data: { [key: string]: any } = {}; _data: { [key: string]: any } = {};
@@ -26,7 +37,6 @@ export abstract class GPXTreeElement<T extends GPXTreeElement<any>> {
abstract getNumberOfTrackPoints(): number; abstract getNumberOfTrackPoints(): number;
abstract getStartTimestamp(): Date | undefined; abstract getStartTimestamp(): Date | undefined;
abstract getEndTimestamp(): Date | undefined; abstract getEndTimestamp(): Date | undefined;
abstract getStatistics(): GPXStatistics;
abstract getSegments(): TrackSegment[]; abstract getSegments(): TrackSegment[];
abstract getTrackPoints(): TrackPoint[]; abstract getTrackPoints(): TrackPoint[];
@@ -66,14 +76,6 @@ abstract class GPXTreeNode<T extends GPXTreeElement<any>> extends GPXTreeElement
return this.children[this.children.length - 1].getEndTimestamp(); return this.children[this.children.length - 1].getEndTimestamp();
} }
getStatistics(): GPXStatistics {
let statistics = new GPXStatistics();
for (let child of this.children) {
statistics.mergeWith(child.getStatistics());
}
return statistics;
}
getSegments(): TrackSegment[] { getSegments(): TrackSegment[] {
return this.children.flatMap((child) => child.getSegments()); return this.children.flatMap((child) => child.getSegments());
} }
@@ -198,8 +200,16 @@ export class GPXFile extends GPXTreeNode<Track> {
}); });
} }
getStatistics(): GPXStatisticsGroup {
let statistics = new GPXStatisticsGroup();
this.forEachSegment((segment) => {
statistics.add(segment.getStatistics());
});
return statistics;
}
getStyle(defaultColor?: string): MergedLineStyles { getStyle(defaultColor?: string): MergedLineStyles {
return this.trk const style = this.trk
.map((track) => track.getStyle()) .map((track) => track.getStyle())
.reduce( .reduce(
(acc, style) => { (acc, style) => {
@@ -209,8 +219,6 @@ export class GPXFile extends GPXTreeNode<Track> {
!acc.color.includes(style['gpx_style:color']) !acc.color.includes(style['gpx_style:color'])
) { ) {
acc.color.push(style['gpx_style:color']); acc.color.push(style['gpx_style:color']);
} else if (defaultColor && !acc.color.includes(defaultColor)) {
acc.color.push(defaultColor);
} }
if ( if (
style && style &&
@@ -234,16 +242,20 @@ export class GPXFile extends GPXTreeNode<Track> {
width: [], width: [],
} }
); );
if (style.color.length === 0 && defaultColor) {
style.color.push(defaultColor);
}
return style;
} }
clone(): GPXFile { clone(): GPXFile {
return new GPXFile({ return new GPXFile({
attributes: structuredClone(this.attributes), attributes: cloneJSON(this.attributes),
metadata: structuredClone(this.metadata), metadata: cloneJSON(this.metadata),
wpt: this.wpt.map((waypoint) => waypoint.clone()), wpt: this.wpt.map((waypoint) => waypoint.clone()),
trk: this.trk.map((track) => track.clone()), trk: this.trk.map((track) => track.clone()),
rte: [], rte: [],
_data: structuredClone(this._data), _data: cloneJSON(this._data),
}); });
} }
@@ -256,7 +268,7 @@ export class GPXFile extends GPXTreeNode<Track> {
toGPXFileType(exclude: string[] = []): GPXFileType { toGPXFileType(exclude: string[] = []): GPXFileType {
let file: GPXFileType = { let file: GPXFileType = {
attributes: structuredClone(this.attributes), attributes: cloneJSON(this.attributes),
metadata: {}, metadata: {},
wpt: this.wpt.map((wpt) => wpt.toWaypointType(exclude)), wpt: this.wpt.map((wpt) => wpt.toWaypointType(exclude)),
trk: this.trk.map((track) => track.toTrackType(exclude)), trk: this.trk.map((track) => track.toTrackType(exclude)),
@@ -270,10 +282,10 @@ export class GPXFile extends GPXTreeNode<Track> {
file.metadata.desc = this.metadata.desc; file.metadata.desc = this.metadata.desc;
} }
if (this.metadata.author) { if (this.metadata.author) {
file.metadata.author = structuredClone(this.metadata.author); file.metadata.author = cloneJSON(this.metadata.author);
} }
if (this.metadata.link) { if (this.metadata.link) {
file.metadata.link = structuredClone(this.metadata.link); file.metadata.link = cloneJSON(this.metadata.link);
} }
if (this.metadata.time && !exclude.includes('time')) { if (this.metadata.time && !exclude.includes('time')) {
file.metadata.time = this.metadata.time; file.metadata.time = this.metadata.time;
@@ -566,11 +578,11 @@ export class Track extends GPXTreeNode<TrackSegment> {
cmt: this.cmt, cmt: this.cmt,
desc: this.desc, desc: this.desc,
src: this.src, src: this.src,
link: structuredClone(this.link), link: cloneJSON(this.link),
type: this.type, type: this.type,
extensions: structuredClone(this.extensions), extensions: cloneJSON(this.extensions),
trkseg: this.trkseg.map((seg) => seg.clone()), trkseg: this.trkseg.map((seg) => seg.clone()),
_data: structuredClone(this._data), _data: cloneJSON(this._data),
}); });
} }
@@ -808,7 +820,9 @@ export class TrackSegment extends GPXTreeLeaf {
_computeStatistics(): GPXStatistics { _computeStatistics(): GPXStatistics {
let statistics = new GPXStatistics(); let statistics = new GPXStatistics();
statistics.global.length = this.trkpt.length;
statistics.local.points = this.trkpt.slice(0); statistics.local.points = this.trkpt.slice(0);
statistics.local.data = this.trkpt.map(() => new TrackPointLocalStatistics());
const points = this.trkpt; const points = this.trkpt;
for (let i = 0; i < points.length; i++) { for (let i = 0; i < points.length; i++) {
@@ -820,19 +834,18 @@ export class TrackSegment extends GPXTreeLeaf {
statistics.global.distance.total += dist; statistics.global.distance.total += dist;
} }
statistics.local.distance.total.push(statistics.global.distance.total); statistics.local.data[i].distance.total = statistics.global.distance.total;
// time // time
if (points[i].time === undefined) { if (points[i].time === undefined) {
statistics.local.time.total.push(0); statistics.local.data[i].time.total = 0;
} else { } else {
if (statistics.global.time.start === undefined) { if (statistics.global.time.start === undefined) {
statistics.global.time.start = points[i].time; statistics.global.time.start = points[i].time;
} }
statistics.global.time.end = points[i].time; statistics.global.time.end = points[i].time;
statistics.local.time.total.push( statistics.local.data[i].time.total =
(points[i].time.getTime() - statistics.global.time.start.getTime()) / 1000 (points[i].time.getTime() - statistics.global.time.start.getTime()) / 1000;
);
} }
// speed // speed
@@ -847,8 +860,8 @@ export class TrackSegment extends GPXTreeLeaf {
} }
} }
statistics.local.distance.moving.push(statistics.global.distance.moving); statistics.local.data[i].distance.moving = statistics.global.distance.moving;
statistics.local.time.moving.push(statistics.global.time.moving); statistics.local.data[i].time.moving = statistics.global.time.moving;
// bounds // bounds
statistics.global.bounds.southWest.lat = Math.min( statistics.global.bounds.southWest.lat = Math.min(
@@ -948,13 +961,22 @@ export class TrackSegment extends GPXTreeLeaf {
? statistics.global.distance.moving / (statistics.global.time.moving / 3600) ? statistics.global.distance.moving / (statistics.global.time.moving / 3600)
: 0; : 0;
statistics.local.speed = timeWindowSmoothing(points, 10000, (start, end) => timeWindowSmoothing(
points[start].time && points[end].time points,
? (3600 * 10000,
(statistics.local.distance.total[end] - (start, end) =>
statistics.local.distance.total[start])) / points[start].time && points[end].time
Math.max((points[end].time.getTime() - points[start].time.getTime()) / 1000, 1) ? (3600 *
: undefined (statistics.local.data[end].distance.total -
statistics.local.data[start].distance.total)) /
Math.max(
(points[end].time.getTime() - points[start].time.getTime()) / 1000,
1
)
: undefined,
(value, index) => {
statistics.local.data[index].speed = value;
}
); );
return statistics; return statistics;
@@ -974,53 +996,65 @@ export class TrackSegment extends GPXTreeLeaf {
let cumulEle = 0; let cumulEle = 0;
let currentStart = start; let currentStart = start;
let currentEnd = start; let currentEnd = start;
let smoothedEle = distanceWindowSmoothing(start, end + 1, statistics, 0.1, (s, e) => { let prevSmoothedEle = 0;
for (let i = currentStart; i < s; i++) { distanceWindowSmoothing(
cumulEle -= this.trkpt[i].ele ?? 0; start,
end + 1,
statistics,
0.1,
(s, e) => {
for (let i = currentStart; i < s; i++) {
cumulEle -= this.trkpt[i].ele ?? 0;
}
for (let i = currentEnd; i <= e; i++) {
cumulEle += this.trkpt[i].ele ?? 0;
}
currentStart = s;
currentEnd = e + 1;
return cumulEle / (e - s + 1);
},
(smoothedEle, j) => {
if (j === start) {
smoothedEle = this.trkpt[start].ele ?? 0;
prevSmoothedEle = smoothedEle;
} else if (j === end) {
smoothedEle = this.trkpt[end].ele ?? 0;
}
const ele = smoothedEle - prevSmoothedEle;
if (ele > 0) {
statistics.global.elevation.gain += ele;
} else if (ele < 0) {
statistics.global.elevation.loss -= ele;
}
prevSmoothedEle = smoothedEle;
if (j < end) {
statistics.local.data[j].elevation.gain = statistics.global.elevation.gain;
statistics.local.data[j].elevation.loss = statistics.global.elevation.loss;
}
} }
for (let i = currentEnd; i <= e; i++) { );
cumulEle += this.trkpt[i].ele ?? 0; }
} if (statistics.global.length > 0) {
currentStart = s; statistics.local.data[statistics.global.length - 1].elevation.gain =
currentEnd = e + 1; statistics.global.elevation.gain;
return cumulEle / (e - s + 1); statistics.local.data[statistics.global.length - 1].elevation.loss =
}); statistics.global.elevation.loss;
smoothedEle[0] = this.trkpt[start].ele ?? 0;
smoothedEle[smoothedEle.length - 1] = this.trkpt[end].ele ?? 0;
for (let j = start; j < end; j++) {
statistics.local.elevation.gain.push(statistics.global.elevation.gain);
statistics.local.elevation.loss.push(statistics.global.elevation.loss);
const ele = smoothedEle[j - start + 1] - smoothedEle[j - start];
if (ele > 0) {
statistics.global.elevation.gain += ele;
} else if (ele < 0) {
statistics.global.elevation.loss -= ele;
}
}
} }
statistics.local.elevation.gain.push(statistics.global.elevation.gain);
statistics.local.elevation.loss.push(statistics.global.elevation.loss);
let slope = [];
let length = [];
for (let i = 0; i < simplified.length - 1; i++) { for (let i = 0; i < simplified.length - 1; i++) {
let start = simplified[i].point._data.index; let start = simplified[i].point._data.index;
let end = simplified[i + 1].point._data.index; let end = simplified[i + 1].point._data.index;
let dist = let dist =
statistics.local.distance.total[end] - statistics.local.distance.total[start]; statistics.local.data[end].distance.total -
statistics.local.data[start].distance.total;
let ele = (simplified[i + 1].point.ele ?? 0) - (simplified[i].point.ele ?? 0); let ele = (simplified[i + 1].point.ele ?? 0) - (simplified[i].point.ele ?? 0);
for (let j = start; j < end + (i + 1 === simplified.length - 1 ? 1 : 0); j++) { for (let j = start; j < end + (i + 1 === simplified.length - 1 ? 1 : 0); j++) {
slope.push((0.1 * ele) / dist); statistics.local.data[j].slope.segment = (0.1 * ele) / dist;
length.push(dist); statistics.local.data[j].slope.length = dist;
} }
} }
statistics.local.slope.segment = slope; distanceWindowSmoothing(
statistics.local.slope.length = length;
statistics.local.slope.at = distanceWindowSmoothing(
0, 0,
this.trkpt.length, this.trkpt.length,
statistics, statistics,
@@ -1028,8 +1062,12 @@ export class TrackSegment extends GPXTreeLeaf {
(start, end) => { (start, end) => {
const ele = this.trkpt[end].ele - this.trkpt[start].ele || 0; const ele = this.trkpt[end].ele - this.trkpt[start].ele || 0;
const dist = const dist =
statistics.local.distance.total[end] - statistics.local.distance.total[start]; statistics.local.data[end].distance.total -
statistics.local.data[start].distance.total;
return dist > 0 ? (0.1 * ele) / dist : 0; return dist > 0 ? (0.1 * ele) / dist : 0;
},
(value, index) => {
statistics.local.data[index].slope.at = value;
} }
); );
} }
@@ -1087,7 +1125,7 @@ export class TrackSegment extends GPXTreeLeaf {
clone(): TrackSegment { clone(): TrackSegment {
return new TrackSegment({ return new TrackSegment({
trkpt: this.trkpt.map((point) => point.clone()), trkpt: this.trkpt.map((point) => point.clone()),
_data: structuredClone(this._data), _data: cloneJSON(this._data),
}); });
} }
@@ -1213,14 +1251,14 @@ export class TrackSegment extends GPXTreeLeaf {
let trkpt = og.trkpt.map( let trkpt = og.trkpt.map(
(point, i) => (point, i) =>
new TrackPoint({ new TrackPoint({
attributes: structuredClone(point.attributes), attributes: cloneJSON(point.attributes),
ele: point.ele, ele: point.ele,
time: new Date( time: new Date(
newStartTimestamp.getTime() + newStartTimestamp.getTime() +
(originalEndTimestamp.getTime() - og.trkpt[i].time.getTime()) (originalEndTimestamp.getTime() - og.trkpt[i].time.getTime())
), ),
extensions: structuredClone(point.extensions), extensions: cloneJSON(point.extensions),
_data: structuredClone(point._data), _data: cloneJSON(point._data),
}) })
); );
@@ -1279,13 +1317,7 @@ export class TrackSegment extends GPXTreeLeaf {
) { ) {
let og = getOriginal(this); // Read as much as possible from the original object because it is faster let og = getOriginal(this); // Read as much as possible from the original object because it is faster
let statistics = og._computeStatistics(); let statistics = og._computeStatistics();
let trkpt = withArtificialTimestamps( let trkpt = withArtificialTimestamps(og.trkpt, totalTime, lastPoint, startTime, statistics);
og.trkpt,
totalTime,
lastPoint,
startTime,
statistics.local.slope.at
);
this.trkpt = freeze(trkpt); // Pre-freeze the array, faster as well this.trkpt = freeze(trkpt); // Pre-freeze the array, faster as well
} }
@@ -1294,6 +1326,7 @@ export class TrackSegment extends GPXTreeLeaf {
} }
} }
const emptyExtensions: Record<string, string> = {};
export class TrackPoint { export class TrackPoint {
[immerable] = true; [immerable] = true;
@@ -1388,7 +1421,7 @@ export class TrackPoint {
this.extensions['gpxtpx:TrackPointExtension'] && this.extensions['gpxtpx:TrackPointExtension'] &&
this.extensions['gpxtpx:TrackPointExtension']['gpxtpx:Extensions'] this.extensions['gpxtpx:TrackPointExtension']['gpxtpx:Extensions']
? this.extensions['gpxtpx:TrackPointExtension']['gpxtpx:Extensions'] ? this.extensions['gpxtpx:TrackPointExtension']['gpxtpx:Extensions']
: {}; : emptyExtensions;
} }
toTrackPointType(exclude: string[] = []): TrackPointType { toTrackPointType(exclude: string[] = []): TrackPointType {
@@ -1464,7 +1497,7 @@ export class TrackPoint {
}, },
ele: this.ele, ele: this.ele,
time: this.time ? new Date(this.time.getTime()) : undefined, time: this.time ? new Date(this.time.getTime()) : undefined,
extensions: this.extensions ? structuredClone(this.extensions) : undefined, extensions: this.extensions ? cloneJSON(this.extensions) : undefined,
_data: { _data: {
index: this._data?.index, index: this._data?.index,
anchor: this._data?.anchor, anchor: this._data?.anchor,
@@ -1566,7 +1599,7 @@ export class Waypoint {
name: this.name, name: this.name,
cmt: this.cmt, cmt: this.cmt,
desc: this.desc, desc: this.desc,
link: structuredClone(this.link), link: cloneJSON(this.link),
sym: this.sym, sym: this.sym,
type: this.type, type: this.type,
}); });
@@ -1609,305 +1642,6 @@ export class Waypoint {
} }
} }
export class GPXStatistics {
global: {
distance: {
moving: number;
total: number;
};
time: {
start: Date | undefined;
end: Date | undefined;
moving: number;
total: number;
};
speed: {
moving: number;
total: number;
};
elevation: {
gain: number;
loss: number;
};
bounds: {
southWest: Coordinates;
northEast: Coordinates;
};
atemp: {
avg: number;
count: number;
};
hr: {
avg: number;
count: number;
};
cad: {
avg: number;
count: number;
};
power: {
avg: number;
count: number;
};
extensions: Record<string, Record<string, number>>;
};
local: {
points: TrackPoint[];
distance: {
moving: number[];
total: number[];
};
time: {
moving: number[];
total: number[];
};
speed: number[];
elevation: {
gain: number[];
loss: number[];
};
slope: {
at: number[];
segment: number[];
length: number[];
};
};
constructor() {
this.global = {
distance: {
moving: 0,
total: 0,
},
time: {
start: undefined,
end: undefined,
moving: 0,
total: 0,
},
speed: {
moving: 0,
total: 0,
},
elevation: {
gain: 0,
loss: 0,
},
bounds: {
southWest: {
lat: 90,
lon: 180,
},
northEast: {
lat: -90,
lon: -180,
},
},
atemp: {
avg: 0,
count: 0,
},
hr: {
avg: 0,
count: 0,
},
cad: {
avg: 0,
count: 0,
},
power: {
avg: 0,
count: 0,
},
extensions: {},
};
this.local = {
points: [],
distance: {
moving: [],
total: [],
},
time: {
moving: [],
total: [],
},
speed: [],
elevation: {
gain: [],
loss: [],
},
slope: {
at: [],
segment: [],
length: [],
},
};
}
mergeWith(other: GPXStatistics): void {
this.local.points = this.local.points.concat(other.local.points);
this.local.distance.total = this.local.distance.total.concat(
other.local.distance.total.map((distance) => distance + this.global.distance.total)
);
this.local.distance.moving = this.local.distance.moving.concat(
other.local.distance.moving.map((distance) => distance + this.global.distance.moving)
);
this.local.time.total = this.local.time.total.concat(
other.local.time.total.map((time) => time + this.global.time.total)
);
this.local.time.moving = this.local.time.moving.concat(
other.local.time.moving.map((time) => time + this.global.time.moving)
);
this.local.elevation.gain = this.local.elevation.gain.concat(
other.local.elevation.gain.map((gain) => gain + this.global.elevation.gain)
);
this.local.elevation.loss = this.local.elevation.loss.concat(
other.local.elevation.loss.map((loss) => loss + this.global.elevation.loss)
);
this.local.speed = this.local.speed.concat(other.local.speed);
this.local.slope.at = this.local.slope.at.concat(other.local.slope.at);
this.local.slope.segment = this.local.slope.segment.concat(other.local.slope.segment);
this.local.slope.length = this.local.slope.length.concat(other.local.slope.length);
this.global.distance.total += other.global.distance.total;
this.global.distance.moving += other.global.distance.moving;
this.global.time.start =
this.global.time.start !== undefined && other.global.time.start !== undefined
? new Date(
Math.min(this.global.time.start.getTime(), other.global.time.start.getTime())
)
: (this.global.time.start ?? other.global.time.start);
this.global.time.end =
this.global.time.end !== undefined && other.global.time.end !== undefined
? new Date(
Math.max(this.global.time.end.getTime(), other.global.time.end.getTime())
)
: (this.global.time.end ?? other.global.time.end);
this.global.time.total += other.global.time.total;
this.global.time.moving += other.global.time.moving;
this.global.speed.moving =
this.global.time.moving > 0
? this.global.distance.moving / (this.global.time.moving / 3600)
: 0;
this.global.speed.total =
this.global.time.total > 0
? this.global.distance.total / (this.global.time.total / 3600)
: 0;
this.global.elevation.gain += other.global.elevation.gain;
this.global.elevation.loss += other.global.elevation.loss;
this.global.bounds.southWest.lat = Math.min(
this.global.bounds.southWest.lat,
other.global.bounds.southWest.lat
);
this.global.bounds.southWest.lon = Math.min(
this.global.bounds.southWest.lon,
other.global.bounds.southWest.lon
);
this.global.bounds.northEast.lat = Math.max(
this.global.bounds.northEast.lat,
other.global.bounds.northEast.lat
);
this.global.bounds.northEast.lon = Math.max(
this.global.bounds.northEast.lon,
other.global.bounds.northEast.lon
);
this.global.atemp.avg =
(this.global.atemp.count * this.global.atemp.avg +
other.global.atemp.count * other.global.atemp.avg) /
Math.max(1, this.global.atemp.count + other.global.atemp.count);
this.global.atemp.count += other.global.atemp.count;
this.global.hr.avg =
(this.global.hr.count * this.global.hr.avg +
other.global.hr.count * other.global.hr.avg) /
Math.max(1, this.global.hr.count + other.global.hr.count);
this.global.hr.count += other.global.hr.count;
this.global.cad.avg =
(this.global.cad.count * this.global.cad.avg +
other.global.cad.count * other.global.cad.avg) /
Math.max(1, this.global.cad.count + other.global.cad.count);
this.global.cad.count += other.global.cad.count;
this.global.power.avg =
(this.global.power.count * this.global.power.avg +
other.global.power.count * other.global.power.avg) /
Math.max(1, this.global.power.count + other.global.power.count);
this.global.power.count += other.global.power.count;
Object.keys(other.global.extensions).forEach((extension) => {
if (this.global.extensions[extension] === undefined) {
this.global.extensions[extension] = {};
}
Object.keys(other.global.extensions[extension]).forEach((value) => {
if (this.global.extensions[extension][value] === undefined) {
this.global.extensions[extension][value] = 0;
}
this.global.extensions[extension][value] +=
other.global.extensions[extension][value];
});
});
}
slice(start: number, end: number): GPXStatistics {
if (start < 0) {
start = 0;
} else if (start >= this.local.points.length) {
return new GPXStatistics();
}
if (end < start) {
return new GPXStatistics();
} else if (end >= this.local.points.length) {
end = this.local.points.length - 1;
}
let statistics = new GPXStatistics();
statistics.local.points = this.local.points.slice(start, end + 1);
statistics.global.distance.total =
this.local.distance.total[end] - this.local.distance.total[start];
statistics.global.distance.moving =
this.local.distance.moving[end] - this.local.distance.moving[start];
statistics.global.time.start = this.local.points[start].time;
statistics.global.time.end = this.local.points[end].time;
statistics.global.time.total = this.local.time.total[end] - this.local.time.total[start];
statistics.global.time.moving = this.local.time.moving[end] - this.local.time.moving[start];
statistics.global.speed.moving =
statistics.global.time.moving > 0
? statistics.global.distance.moving / (statistics.global.time.moving / 3600)
: 0;
statistics.global.speed.total =
statistics.global.time.total > 0
? statistics.global.distance.total / (statistics.global.time.total / 3600)
: 0;
statistics.global.elevation.gain =
this.local.elevation.gain[end] - this.local.elevation.gain[start];
statistics.global.elevation.loss =
this.local.elevation.loss[end] - this.local.elevation.loss[start];
statistics.global.bounds.southWest.lat = this.global.bounds.southWest.lat;
statistics.global.bounds.southWest.lon = this.global.bounds.southWest.lon;
statistics.global.bounds.northEast.lat = this.global.bounds.northEast.lat;
statistics.global.bounds.northEast.lon = this.global.bounds.northEast.lon;
statistics.global.atemp = this.global.atemp;
statistics.global.hr = this.global.hr;
statistics.global.cad = this.global.cad;
statistics.global.power = this.global.power;
return statistics;
}
}
const earthRadius = 6371008.8; const earthRadius = 6371008.8;
export function distance( export function distance(
coord1: TrackPoint | Coordinates, coord1: TrackPoint | Coordinates,
@@ -1941,9 +1675,9 @@ export function getElevationDistanceFunction(statistics: GPXStatistics) {
if (point1.ele === undefined || point2.ele === undefined || point3.ele === undefined) { if (point1.ele === undefined || point2.ele === undefined || point3.ele === undefined) {
return 0; return 0;
} }
let x1 = statistics.local.distance.total[point1._data.index] * 1000; let x1 = statistics.local.data[point1._data.index].distance.total * 1000;
let x2 = statistics.local.distance.total[point2._data.index] * 1000; let x2 = statistics.local.data[point2._data.index].distance.total * 1000;
let x3 = statistics.local.distance.total[point3._data.index] * 1000; let x3 = statistics.local.data[point3._data.index].distance.total * 1000;
let y1 = point1.ele; let y1 = point1.ele;
let y2 = point2.ele; let y2 = point2.ele;
let y3 = point3.ele; let y3 = point3.ele;
@@ -1962,10 +1696,9 @@ function windowSmoothing(
right: number, right: number,
distance: (index1: number, index2: number) => number, distance: (index1: number, index2: number) => number,
window: number, window: number,
compute: (start: number, end: number) => number compute: (start: number, end: number) => number,
): number[] { callback: (value: number, index: number) => void
let result = []; ): void {
let start = left; let start = left;
for (var i = left; i < right; i++) { for (var i = left; i < right; i++) {
while (start + 1 < i && distance(start, i) > window) { while (start + 1 < i && distance(start, i) > window) {
@@ -1975,10 +1708,8 @@ function windowSmoothing(
while (end < right && distance(i, end) <= window) { while (end < right && distance(i, end) <= window) {
end++; end++;
} }
result.push(compute(start, end - 1)); callback(compute(start, end - 1), i);
} }
return result;
} }
function distanceWindowSmoothing( function distanceWindowSmoothing(
@@ -1986,30 +1717,35 @@ function distanceWindowSmoothing(
right: number, right: number,
statistics: GPXStatistics, statistics: GPXStatistics,
window: number, window: number,
compute: (start: number, end: number) => number compute: (start: number, end: number) => number,
): number[] { callback: (value: number, index: number) => void
return windowSmoothing( ): void {
windowSmoothing(
left, left,
right, right,
(index1, index2) => (index1, index2) =>
statistics.local.distance.total[index2] - statistics.local.distance.total[index1], statistics.local.data[index2].distance.total -
statistics.local.data[index1].distance.total,
window, window,
compute compute,
callback
); );
} }
function timeWindowSmoothing( function timeWindowSmoothing(
points: TrackPoint[], points: TrackPoint[],
window: number, window: number,
compute: (start: number, end: number) => number compute: (start: number, end: number) => number,
): number[] { callback: (value: number, index: number) => void
return windowSmoothing( ): void {
windowSmoothing(
0, 0,
points.length, points.length,
(index1, index2) => (index1, index2) =>
points[index2].time?.getTime() - points[index1].time?.getTime() || 2 * window, points[index2].time?.getTime() - points[index1].time?.getTime() || 2 * window,
window, window,
compute compute,
callback
); );
} }
@@ -2061,14 +1797,14 @@ function withArtificialTimestamps(
totalTime: number, totalTime: number,
lastPoint: TrackPoint | undefined, lastPoint: TrackPoint | undefined,
startTime: Date, startTime: Date,
slope: number[] statistics: GPXStatistics
): TrackPoint[] { ): TrackPoint[] {
let weight = []; let weight = [];
let totalWeight = 0; let totalWeight = 0;
for (let i = 0; i < points.length - 1; i++) { for (let i = 0; i < points.length - 1; i++) {
let dist = distance(points[i].getCoordinates(), points[i + 1].getCoordinates()); let dist = distance(points[i].getCoordinates(), points[i + 1].getCoordinates());
let w = dist * (0.5 + 1 / (1 + Math.exp(-0.2 * slope[i]))); let w = dist * (0.5 + 1 / (1 + Math.exp(-0.2 * statistics.local.data[i].slope.at)));
weight.push(w); weight.push(w);
totalWeight += w; totalWeight += w;
} }

View File

@@ -1,4 +1,5 @@
export * from './gpx'; export * from './gpx';
export * from './statistics';
export { Coordinates, LineStyleExtension, WaypointType } from './types'; export { Coordinates, LineStyleExtension, WaypointType } from './types';
export { parseGPX, buildGPX } from './io'; export { parseGPX, buildGPX } from './io';
export * from './simplify'; export * from './simplify';

391
gpx/src/statistics.ts Normal file
View File

@@ -0,0 +1,391 @@
import { TrackPoint } from './gpx';
import { Coordinates } from './types';
export class GPXGlobalStatistics {
length: number;
distance: {
moving: number;
total: number;
};
time: {
start: Date | undefined;
end: Date | undefined;
moving: number;
total: number;
};
speed: {
moving: number;
total: number;
};
elevation: {
gain: number;
loss: number;
};
bounds: {
southWest: Coordinates;
northEast: Coordinates;
};
atemp: {
avg: number;
count: number;
};
hr: {
avg: number;
count: number;
};
cad: {
avg: number;
count: number;
};
power: {
avg: number;
count: number;
};
extensions: Record<string, Record<string, number>>;
constructor() {
this.length = 0;
this.distance = {
moving: 0,
total: 0,
};
this.time = {
start: undefined,
end: undefined,
moving: 0,
total: 0,
};
this.speed = {
moving: 0,
total: 0,
};
this.elevation = {
gain: 0,
loss: 0,
};
this.bounds = {
southWest: {
lat: 90,
lon: 180,
},
northEast: {
lat: -90,
lon: -180,
},
};
this.atemp = {
avg: 0,
count: 0,
};
this.hr = {
avg: 0,
count: 0,
};
this.cad = {
avg: 0,
count: 0,
};
this.power = {
avg: 0,
count: 0,
};
this.extensions = {};
}
mergeWith(other: GPXGlobalStatistics): void {
this.length += other.length;
this.distance.total += other.distance.total;
this.distance.moving += other.distance.moving;
this.time.start =
this.time.start !== undefined && other.time.start !== undefined
? new Date(Math.min(this.time.start.getTime(), other.time.start.getTime()))
: (this.time.start ?? other.time.start);
this.time.end =
this.time.end !== undefined && other.time.end !== undefined
? new Date(Math.max(this.time.end.getTime(), other.time.end.getTime()))
: (this.time.end ?? other.time.end);
this.time.total += other.time.total;
this.time.moving += other.time.moving;
this.speed.moving =
this.time.moving > 0 ? this.distance.moving / (this.time.moving / 3600) : 0;
this.speed.total = this.time.total > 0 ? this.distance.total / (this.time.total / 3600) : 0;
this.elevation.gain += other.elevation.gain;
this.elevation.loss += other.elevation.loss;
this.bounds.southWest.lat = Math.min(this.bounds.southWest.lat, other.bounds.southWest.lat);
this.bounds.southWest.lon = Math.min(this.bounds.southWest.lon, other.bounds.southWest.lon);
this.bounds.northEast.lat = Math.max(this.bounds.northEast.lat, other.bounds.northEast.lat);
this.bounds.northEast.lon = Math.max(this.bounds.northEast.lon, other.bounds.northEast.lon);
this.atemp.avg =
(this.atemp.count * this.atemp.avg + other.atemp.count * other.atemp.avg) /
Math.max(1, this.atemp.count + other.atemp.count);
this.atemp.count += other.atemp.count;
this.hr.avg =
(this.hr.count * this.hr.avg + other.hr.count * other.hr.avg) /
Math.max(1, this.hr.count + other.hr.count);
this.hr.count += other.hr.count;
this.cad.avg =
(this.cad.count * this.cad.avg + other.cad.count * other.cad.avg) /
Math.max(1, this.cad.count + other.cad.count);
this.cad.count += other.cad.count;
this.power.avg =
(this.power.count * this.power.avg + other.power.count * other.power.avg) /
Math.max(1, this.power.count + other.power.count);
this.power.count += other.power.count;
Object.keys(other.extensions).forEach((extension) => {
if (this.extensions[extension] === undefined) {
this.extensions[extension] = {};
}
Object.keys(other.extensions[extension]).forEach((value) => {
if (this.extensions[extension][value] === undefined) {
this.extensions[extension][value] = 0;
}
this.extensions[extension][value] += other.extensions[extension][value];
});
});
}
}
export class TrackPointLocalStatistics {
distance: {
moving: number;
total: number;
};
time: {
moving: number;
total: number;
};
speed: number;
elevation: {
gain: number;
loss: number;
};
slope: {
at: number;
segment: number;
length: number;
};
constructor() {
this.distance = {
moving: 0,
total: 0,
};
this.time = {
moving: 0,
total: 0,
};
this.speed = 0;
this.elevation = {
gain: 0,
loss: 0,
};
this.slope = {
at: 0,
segment: 0,
length: 0,
};
}
}
export class GPXLocalStatistics {
points: TrackPoint[];
data: TrackPointLocalStatistics[];
constructor() {
this.points = [];
this.data = [];
}
}
export type TrackPointWithLocalStatistics = {
trkpt: TrackPoint;
} & TrackPointLocalStatistics;
export class GPXStatistics {
global: GPXGlobalStatistics;
local: GPXLocalStatistics;
constructor() {
this.global = new GPXGlobalStatistics();
this.local = new GPXLocalStatistics();
}
sliced(start: number, end: number): GPXGlobalStatistics {
if (start < 0) {
start = 0;
} else if (start >= this.global.length) {
return new GPXGlobalStatistics();
}
if (end < start) {
return new GPXGlobalStatistics();
} else if (end >= this.global.length) {
end = this.global.length - 1;
}
if (start === 0 && end === this.global.length - 1) {
return this.global;
}
let statistics = new GPXGlobalStatistics();
statistics.length = end - start + 1;
statistics.distance.total =
this.local.data[end].distance.total - this.local.data[start].distance.total;
statistics.distance.moving =
this.local.data[end].distance.moving - this.local.data[start].distance.moving;
statistics.time.start = this.local.points[start].time;
statistics.time.end = this.local.points[end].time;
statistics.time.total = this.local.data[end].time.total - this.local.data[start].time.total;
statistics.time.moving =
this.local.data[end].time.moving - this.local.data[start].time.moving;
statistics.speed.moving =
statistics.time.moving > 0
? statistics.distance.moving / (statistics.time.moving / 3600)
: 0;
statistics.speed.total =
statistics.time.total > 0
? statistics.distance.total / (statistics.time.total / 3600)
: 0;
statistics.elevation.gain =
this.local.data[end].elevation.gain - this.local.data[start].elevation.gain;
statistics.elevation.loss =
this.local.data[end].elevation.loss - this.local.data[start].elevation.loss;
statistics.bounds.southWest.lat = this.global.bounds.southWest.lat;
statistics.bounds.southWest.lon = this.global.bounds.southWest.lon;
statistics.bounds.northEast.lat = this.global.bounds.northEast.lat;
statistics.bounds.northEast.lon = this.global.bounds.northEast.lon;
statistics.atemp = this.global.atemp;
statistics.hr = this.global.hr;
statistics.cad = this.global.cad;
statistics.power = this.global.power;
return statistics;
}
}
export class GPXStatisticsGroup {
private _statistics: GPXStatistics[];
private _cumulative: GPXGlobalStatistics[];
private _slice: [number, number] | null = null;
global: GPXGlobalStatistics;
constructor() {
this._statistics = [];
this._cumulative = [new GPXGlobalStatistics()];
this.global = new GPXGlobalStatistics();
}
add(statistics: GPXStatistics | GPXStatisticsGroup): void {
if (statistics instanceof GPXStatisticsGroup) {
statistics._statistics.forEach((stats) => this._add(stats));
} else {
this._add(statistics);
}
}
_add(statistics: GPXStatistics): void {
this._statistics.push(statistics);
const cumulative = new GPXGlobalStatistics();
cumulative.mergeWith(this._cumulative[this._cumulative.length - 1]);
cumulative.mergeWith(statistics.global);
this._cumulative.push(cumulative);
this.global.mergeWith(statistics.global);
}
sliced(start: number, end: number): GPXGlobalStatistics {
let sliced = new GPXGlobalStatistics();
for (let i = 0; i < this._statistics.length; i++) {
const statistics = this._statistics[i];
const cumulative = this._cumulative[i];
if (start < cumulative.length + statistics.global.length && end >= cumulative.length) {
const localStart = Math.max(0, start - cumulative.length);
const localEnd = Math.min(statistics.global.length - 1, end - cumulative.length);
sliced.mergeWith(statistics.sliced(localStart, localEnd));
}
}
return sliced;
}
getTrackPoint(index: number): TrackPointWithLocalStatistics | undefined {
if (this._slice !== null) {
index += this._slice[0];
}
for (let i = 0; i < this._statistics.length; i++) {
const statistics = this._statistics[i];
const cumulative = this._cumulative[i];
if (index < cumulative.length + statistics.global.length) {
return this._getTrackPoint(cumulative, statistics, index - cumulative.length);
}
}
return undefined;
}
_getTrackPoint(
cumulative: GPXGlobalStatistics,
statistics: GPXStatistics,
index: number
): TrackPointWithLocalStatistics {
const point = statistics.local.points[index];
return {
trkpt: point,
distance: {
moving: statistics.local.data[index].distance.moving + cumulative.distance.moving,
total: statistics.local.data[index].distance.total + cumulative.distance.total,
},
time: {
moving: statistics.local.data[index].time.moving + cumulative.time.moving,
total: statistics.local.data[index].time.total + cumulative.time.total,
},
speed: statistics.local.data[index].speed,
elevation: {
gain: statistics.local.data[index].elevation.gain + cumulative.elevation.gain,
loss: statistics.local.data[index].elevation.loss + cumulative.elevation.loss,
},
slope: {
at: statistics.local.data[index].slope.at,
segment: statistics.local.data[index].slope.segment,
length: statistics.local.data[index].slope.length,
},
};
}
forEachTrackPoint(
callback: (
point: TrackPoint,
distance: number,
speed: number,
slope: { at: number; segment: number; length: number },
index: number
) => void
): void {
for (let i = 0; i < this._statistics.length; i++) {
const statistics = this._statistics[i];
const cumulative = this._cumulative[i];
statistics.local.points.forEach((point, index) =>
callback(
point,
cumulative.distance.total + statistics.local.data[index].distance.total,
statistics.local.data[index].speed,
statistics.local.data[index].slope,
cumulative.length + index
)
);
}
}
}

View File

@@ -1 +1 @@
PUBLIC_MAPBOX_TOKEN=YOUR_MAPBOX_TOKEN PUBLIC_MAPTILER_KEY=YOUR_MAPTILER_KEY

View File

@@ -1,3 +0,0 @@
src/lib/components/ui
src/lib/docs/**/*.mdx
**/*.webmanifest

1222
website/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -10,8 +10,8 @@
"preview": "vite preview", "preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "prettier --check . --config ../.prettierrc && eslint .", "lint": "prettier --check . --config ../.prettierrc --ignore-path ../.prettierignore --ignore-path ./.gitignore && eslint .",
"format": "prettier --write . --config ../.prettierrc" "format": "prettier --write . --config ../.prettierrc --ignore-path ../.prettierignore --ignore-path ./.gitignore"
}, },
"devDependencies": { "devDependencies": {
"@lucide/svelte": "^0.544.0", "@lucide/svelte": "^0.544.0",
@@ -23,10 +23,9 @@
"@types/eslint": "^9.6.1", "@types/eslint": "^9.6.1",
"@types/events": "^3.0.3", "@types/events": "^3.0.3",
"@types/file-saver": "^2.0.7", "@types/file-saver": "^2.0.7",
"@types/mapbox__sphericalmercator": "^1.2.3",
"@types/mapbox__tilebelt": "^1.0.4", "@types/mapbox__tilebelt": "^1.0.4",
"@types/mapbox-gl": "^3.4.1",
"@types/node": "^22.15.30", "@types/node": "^22.15.30",
"@types/png.js": "^0.2.3",
"@types/sanitize-html": "^2.16.0", "@types/sanitize-html": "^2.16.0",
"@types/sortablejs": "^1.15.8", "@types/sortablejs": "^1.15.8",
"@typescript-eslint/eslint-plugin": "^8.33.1", "@typescript-eslint/eslint-plugin": "^8.33.1",
@@ -62,10 +61,9 @@
"dependencies": { "dependencies": {
"@docsearch/js": "^3.9.0", "@docsearch/js": "^3.9.0",
"@internationalized/date": "^3.8.2", "@internationalized/date": "^3.8.2",
"@mapbox/mapbox-gl-geocoder": "^5.0.3",
"@mapbox/sphericalmercator": "^2.0.1", "@mapbox/sphericalmercator": "^2.0.1",
"@mapbox/tilebelt": "^2.0.2", "@mapbox/tilebelt": "^2.0.2",
"@types/mapbox__sphericalmercator": "^1.2.3", "@maplibre/maplibre-gl-geocoder": "^1.9.4",
"chart.js": "^4.5.1", "chart.js": "^4.5.1",
"chartjs-plugin-zoom": "^2.2.0", "chartjs-plugin-zoom": "^2.2.0",
"clsx": "^2.1.1", "clsx": "^2.1.1",
@@ -74,9 +72,8 @@
"gpx": "file:../gpx", "gpx": "file:../gpx",
"immer": "^10.1.1", "immer": "^10.1.1",
"jszip": "^3.10.1", "jszip": "^3.10.1",
"mapbox-gl": "^3.17.0",
"mapillary-js": "^4.1.2", "mapillary-js": "^4.1.2",
"png.js": "^0.2.1", "maplibre-gl": "^5.16.0",
"sanitize-html": "^2.17.0", "sanitize-html": "^2.17.0",
"sortablejs": "^1.15.6", "sortablejs": "^1.15.6",
"tailwind-merge": "^3.3.0" "tailwind-merge": "^3.3.0"

View File

@@ -17,7 +17,6 @@
} }
}, },
"sprite": "https://demotiles.maplibre.org/styles/osm-bright-gl-style/sprite", "sprite": "https://demotiles.maplibre.org/styles/osm-bright-gl-style/sprite",
"glyphs": "https://api.maptiler.com/fonts/{fontstack}/{range}.pbf?key={key}",
"layers": [ "layers": [
{ {
"id": "background", "id": "background",

View File

Before

Width:  |  Height:  |  Size: 3.6 MiB

After

Width:  |  Height:  |  Size: 3.6 MiB

View File

Before

Width:  |  Height:  |  Size: 1.5 MiB

After

Width:  |  Height:  |  Size: 1.5 MiB

View File

@@ -22,15 +22,18 @@ import {
Binoculars, Binoculars,
Toilet, Toilet,
} from 'lucide-static'; } from 'lucide-static';
import { type StyleSpecification } from 'mapbox-gl'; import { type RasterDEMSourceSpecification, type StyleSpecification } from 'maplibre-gl';
import ignFrTopo from './custom/ign-fr-topo.json'; import ignFrTopo from './custom/ign-fr-topo.json';
import ignFrPlan from './custom/ign-fr-plan.json'; import ignFrPlan from './custom/ign-fr-plan.json';
import ignFrSatellite from './custom/ign-fr-satellite.json'; import ignFrSatellite from './custom/ign-fr-satellite.json';
import bikerouterGravel from './custom/bikerouter-gravel.json'; import bikerouterGravel from './custom/bikerouter-gravel.json';
export const maptilerKeyPlaceHolder = 'MAPTILER_KEY';
export const basemaps: { [key: string]: string | StyleSpecification } = { export const basemaps: { [key: string]: string | StyleSpecification } = {
mapboxOutdoors: 'mapbox://styles/mapbox/outdoors-v12', maptilerTopo: `https://api.maptiler.com/maps/topo-v4/style.json?key=${maptilerKeyPlaceHolder}`,
mapboxSatellite: 'mapbox://styles/mapbox/satellite-streets-v12', maptilerOutdoors: `https://api.maptiler.com/maps/outdoor-v4/style.json?key=${maptilerKeyPlaceHolder}`,
maptilerSatellite: `https://api.maptiler.com/maps/hybrid-v4/style.json?key=${maptilerKeyPlaceHolder}`,
openStreetMap: { openStreetMap: {
version: 8, version: 8,
sources: { sources: {
@@ -368,6 +371,42 @@ export const overlays: { [key: string]: string | StyleSpecification } = {
], ],
}, },
bikerouterGravel: bikerouterGravel as StyleSpecification, bikerouterGravel: bikerouterGravel as StyleSpecification,
openRailwayMap: {
version: 8,
sources: {
openRailwayMap: {
type: 'raster',
tiles: ['https://tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png'],
tileSize: 256,
maxzoom: 19,
attribution:
'Data <a href="https://www.openstreetmap.org/copyright">&copy; OpenStreetMap contributors</a>, Style: <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA 2.0</a> <a href="http://www.openrailwaymap.org/">OpenRailwayMap</a>',
},
},
layers: [
{
id: 'openRailwayMap',
type: 'raster',
source: 'openRailwayMap',
},
],
},
mapterhornHillshade: {
version: 8,
sources: {
mapterhornHillshade: {
type: 'raster-dem',
url: 'https://tiles.mapterhorn.com/tilejson.json',
},
},
layers: [
{
id: 'mapterhornHillshade',
type: 'hillshade',
source: 'mapterhornHillshade',
},
],
},
swisstopoSlope: { swisstopoSlope: {
version: 8, version: 8,
sources: { sources: {
@@ -737,8 +776,9 @@ export type LayerTreeType = { [key: string]: LayerTreeType | boolean };
export const basemapTree: LayerTreeType = { export const basemapTree: LayerTreeType = {
basemaps: { basemaps: {
world: { world: {
mapboxOutdoors: true, maptilerTopo: true,
mapboxSatellite: true, maptilerOutdoors: true,
maptilerSatellite: true,
openStreetMap: true, openStreetMap: true,
openTopoMap: true, openTopoMap: true,
openHikingMap: true, openHikingMap: true,
@@ -799,8 +839,10 @@ export const overlayTree: LayerTreeType = {
waymarkedTrailsHorseRiding: true, waymarkedTrailsHorseRiding: true,
waymarkedTrailsWinter: true, waymarkedTrailsWinter: true,
}, },
cyclOSMlite: true,
bikerouterGravel: true, bikerouterGravel: true,
cyclOSMlite: true,
mapterhornHillshade: true,
openRailwayMap: true,
}, },
countries: { countries: {
france: { france: {
@@ -869,7 +911,7 @@ export const overpassTree: LayerTreeType = {
}; };
// Default basemap used // Default basemap used
export const defaultBasemap = 'mapboxOutdoors'; export const defaultBasemap = 'maptilerTopo';
// Default overlays used (none) // Default overlays used (none)
export const defaultOverlays: LayerTreeType = { export const defaultOverlays: LayerTreeType = {
@@ -883,8 +925,10 @@ export const defaultOverlays: LayerTreeType = {
waymarkedTrailsHorseRiding: false, waymarkedTrailsHorseRiding: false,
waymarkedTrailsWinter: false, waymarkedTrailsWinter: false,
}, },
cyclOSMlite: false,
bikerouterGravel: false, bikerouterGravel: false,
cyclOSMlite: false,
mapterhornHillshade: false,
openRailwayMap: false,
}, },
countries: { countries: {
france: { france: {
@@ -956,8 +1000,9 @@ export const defaultOverpassQueries: LayerTreeType = {
export const defaultBasemapTree: LayerTreeType = { export const defaultBasemapTree: LayerTreeType = {
basemaps: { basemaps: {
world: { world: {
mapboxOutdoors: true, maptilerTopo: true,
mapboxSatellite: true, maptilerOutdoors: true,
maptilerSatellite: true,
openStreetMap: true, openStreetMap: true,
openTopoMap: true, openTopoMap: true,
openHikingMap: true, openHikingMap: true,
@@ -1018,8 +1063,10 @@ export const defaultOverlayTree: LayerTreeType = {
waymarkedTrailsHorseRiding: false, waymarkedTrailsHorseRiding: false,
waymarkedTrailsWinter: false, waymarkedTrailsWinter: false,
}, },
cyclOSMlite: false,
bikerouterGravel: false, bikerouterGravel: false,
cyclOSMlite: false,
mapterhornHillshade: false,
openRailwayMap: false,
}, },
countries: { countries: {
france: { france: {
@@ -1094,7 +1141,7 @@ export type CustomLayer = {
maxZoom: number; maxZoom: number;
layerType: 'basemap' | 'overlay'; layerType: 'basemap' | 'overlay';
resourceType: 'raster' | 'vector'; resourceType: 'raster' | 'vector';
value: string | {}; value: string | maplibregl.StyleSpecification;
}; };
type OverpassQueryData = { type OverpassQueryData = {
@@ -1411,3 +1458,16 @@ export const overpassQueryData: Record<string, OverpassQueryData> = {
symbol: 'Anchor', symbol: 'Anchor',
}, },
}; };
export const terrainSources: { [key: string]: RasterDEMSourceSpecification } = {
'maptiler-dem': {
type: 'raster-dem',
url: `https://api.maptiler.com/tiles/terrain-rgb-v2/tiles.json?key=${maptilerKeyPlaceHolder}`,
},
mapterhorn: {
type: 'raster-dem',
url: 'https://tiles.mapterhorn.com/tilejson.json',
},
};
export const defaultTerrainSource = 'maptiler-dem';

View File

@@ -18,7 +18,7 @@
href="https://github.com/gpxstudio/gpx.studio/blob/main/LICENSE" href="https://github.com/gpxstudio/gpx.studio/blob/main/LICENSE"
target="_blank" target="_blank"
> >
MIT © 2025 gpx.studio MIT © 2026 gpx.studio
</Button> </Button>
<LanguageSelect class="w-40 mt-3" /> <LanguageSelect class="w-40 mt-3" />
</div> </div>

View File

@@ -6,7 +6,7 @@
import { MoveDownRight, MoveUpRight, Ruler, Timer, Zap } from '@lucide/svelte'; import { MoveDownRight, MoveUpRight, Ruler, Timer, Zap } from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte'; import { i18n } from '$lib/i18n.svelte';
import type { GPXStatistics } from 'gpx'; import type { GPXGlobalStatistics, GPXStatisticsGroup } from 'gpx';
import type { Readable } from 'svelte/store'; import type { Readable } from 'svelte/store';
import { settings } from '$lib/logic/settings'; import { settings } from '$lib/logic/settings';
@@ -18,14 +18,14 @@
orientation, orientation,
panelSize, panelSize,
}: { }: {
gpxStatistics: Readable<GPXStatistics>; gpxStatistics: Readable<GPXStatisticsGroup>;
slicedGPXStatistics: Readable<[GPXStatistics, number, number] | undefined>; slicedGPXStatistics: Readable<[GPXGlobalStatistics, number, number] | undefined>;
orientation: 'horizontal' | 'vertical'; orientation: 'horizontal' | 'vertical';
panelSize: number; panelSize: number;
} = $props(); } = $props();
let statistics = $derived( let statistics = $derived(
$slicedGPXStatistics !== undefined ? $slicedGPXStatistics[0] : $gpxStatistics $slicedGPXStatistics !== undefined ? $slicedGPXStatistics[0] : $gpxStatistics.global
); );
</script> </script>
@@ -42,15 +42,15 @@
<Tooltip label={i18n._('quantities.distance')}> <Tooltip label={i18n._('quantities.distance')}>
<span class="flex flex-row items-center"> <span class="flex flex-row items-center">
<Ruler size="16" class="mr-1" /> <Ruler size="16" class="mr-1" />
<WithUnits value={statistics.global.distance.total} type="distance" /> <WithUnits value={statistics.distance.total} type="distance" />
</span> </span>
</Tooltip> </Tooltip>
<Tooltip label={i18n._('quantities.elevation_gain_loss')}> <Tooltip label={i18n._('quantities.elevation_gain_loss')}>
<span class="flex flex-row items-center"> <span class="flex flex-row items-center">
<MoveUpRight size="16" class="mr-1" /> <MoveUpRight size="16" class="mr-1" />
<WithUnits value={statistics.global.elevation.gain} type="elevation" /> <WithUnits value={statistics.elevation.gain} type="elevation" />
<MoveDownRight size="16" class="mx-1" /> <MoveDownRight size="16" class="mx-1" />
<WithUnits value={statistics.global.elevation.loss} type="elevation" /> <WithUnits value={statistics.elevation.loss} type="elevation" />
</span> </span>
</Tooltip> </Tooltip>
{#if panelSize > 120 || orientation === 'horizontal'} {#if panelSize > 120 || orientation === 'horizontal'}
@@ -64,13 +64,9 @@
> >
<span class="flex flex-row items-center"> <span class="flex flex-row items-center">
<Zap size="16" class="mr-1" /> <Zap size="16" class="mr-1" />
<WithUnits <WithUnits value={statistics.speed.moving} type="speed" showUnits={false} />
value={statistics.global.speed.moving}
type="speed"
showUnits={false}
/>
<span class="mx-1">/</span> <span class="mx-1">/</span>
<WithUnits value={statistics.global.speed.total} type="speed" /> <WithUnits value={statistics.speed.total} type="speed" />
</span> </span>
</Tooltip> </Tooltip>
{/if} {/if}
@@ -83,9 +79,9 @@
> >
<span class="flex flex-row items-center"> <span class="flex flex-row items-center">
<Timer size="16" class="mr-1" /> <Timer size="16" class="mr-1" />
<WithUnits value={statistics.global.time.moving} type="time" /> <WithUnits value={statistics.time.moving} type="time" />
<span class="mx-1">/</span> <span class="mx-1">/</span>
<WithUnits value={statistics.global.time.total} type="time" /> <WithUnits value={statistics.time.total} type="time" />
</span> </span>
</Tooltip> </Tooltip>
{/if} {/if}

View File

@@ -8,7 +8,7 @@
...others ...others
}: { }: {
iconOnly?: boolean; iconOnly?: boolean;
company?: 'gpx.studio' | 'mapbox' | 'github' | 'crowdin' | 'facebook' | 'reddit'; company?: 'gpx.studio' | 'maptiler' | 'github' | 'crowdin' | 'facebook' | 'reddit';
[key: string]: any; [key: string]: any;
} = $props(); } = $props();
</script> </script>
@@ -19,10 +19,10 @@
alt="Logo of gpx.studio." alt="Logo of gpx.studio."
{...others} {...others}
/> />
{:else if company === 'mapbox'} {:else if company === 'maptiler'}
<img <img
src="{base}/mapbox-logo-{mode.current === 'dark' ? 'white' : 'black'}.svg" src="{base}/maptiler-logo{mode.current === 'dark' ? '-dark' : ''}.svg"
alt="Logo of Mapbox." alt="Logo of Maptiler."
{...others} {...others}
/> />
{:else if company === 'github'} {:else if company === 'github'}

View File

@@ -1,10 +1,10 @@
<script lang="ts"> <script lang="ts">
import mapboxOutdoorsMap from '$lib/assets/img/home/mapbox-outdoors.png?enhanced'; import maptilerTopoMap from '$lib/assets/img/home/maptiler-topo.png?enhanced';
import waymarkedMap from '$lib/assets/img/home/waymarked.png?enhanced'; import waymarkedMap from '$lib/assets/img/home/waymarked.png?enhanced';
</script> </script>
<div class="relative h-80 aspect-square rounded-2xl shadow-xl overflow-clip"> <div class="relative h-80 aspect-square rounded-2xl shadow-xl overflow-clip">
<enhanced:img src={mapboxOutdoorsMap} alt="Mapbox Outdoors map screenshot." class="absolute" /> <enhanced:img src={maptilerTopoMap} alt="MapTiler Topo map screenshot." class="absolute" />
<enhanced:img <enhanced:img
src={waymarkedMap} src={waymarkedMap}
alt="Waymarked Trails map screenshot." alt="Waymarked Trails map screenshot."

View File

@@ -18,7 +18,7 @@
Construction, Construction,
} from '@lucide/svelte'; } from '@lucide/svelte';
import type { Readable, Writable } from 'svelte/store'; import type { Readable, Writable } from 'svelte/store';
import type { GPXStatistics } from 'gpx'; import type { Coordinates, GPXGlobalStatistics, GPXStatisticsGroup } from 'gpx';
import { settings } from '$lib/logic/settings'; import { settings } from '$lib/logic/settings';
import { i18n } from '$lib/i18n.svelte'; import { i18n } from '$lib/i18n.svelte';
import { ElevationProfile } from '$lib/components/elevation-profile/elevation-profile'; import { ElevationProfile } from '$lib/components/elevation-profile/elevation-profile';
@@ -28,12 +28,14 @@
let { let {
gpxStatistics, gpxStatistics,
slicedGPXStatistics, slicedGPXStatistics,
hoveredPoint,
additionalDatasets, additionalDatasets,
elevationFill, elevationFill,
showControls = true, showControls = true,
}: { }: {
gpxStatistics: Readable<GPXStatistics>; gpxStatistics: Readable<GPXStatisticsGroup>;
slicedGPXStatistics: Writable<[GPXStatistics, number, number] | undefined>; slicedGPXStatistics: Writable<[GPXGlobalStatistics, number, number] | undefined>;
hoveredPoint: Writable<Coordinates | null>;
additionalDatasets: Writable<string[]>; additionalDatasets: Writable<string[]>;
elevationFill: Writable<'slope' | 'surface' | 'highway' | undefined>; elevationFill: Writable<'slope' | 'surface' | 'highway' | undefined>;
showControls?: boolean; showControls?: boolean;
@@ -47,6 +49,7 @@
elevationProfile = new ElevationProfile( elevationProfile = new ElevationProfile(
gpxStatistics, gpxStatistics,
slicedGPXStatistics, slicedGPXStatistics,
hoveredPoint,
additionalDatasets, additionalDatasets,
elevationFill, elevationFill,
canvas, canvas,

View File

@@ -20,10 +20,8 @@ import Chart, {
type ScriptableLineSegmentContext, type ScriptableLineSegmentContext,
type TooltipItem, type TooltipItem,
} from 'chart.js/auto'; } from 'chart.js/auto';
import mapboxgl from 'mapbox-gl';
import { get, type Readable, type Writable } from 'svelte/store'; import { get, type Readable, type Writable } from 'svelte/store';
import { map } from '$lib/components/map/map'; import type { Coordinates, GPXGlobalStatistics, GPXStatisticsGroup } from 'gpx';
import type { GPXStatistics } from 'gpx';
import { mode } from 'mode-watcher'; import { mode } from 'mode-watcher';
import { getHighwayColor, getSlopeColor, getSurfaceColor } from '$lib/assets/colors'; import { getHighwayColor, getSlopeColor, getSurfaceColor } from '$lib/assets/colors';
@@ -42,7 +40,7 @@ interface ElevationProfilePoint {
length: number; length: number;
}; };
extensions: Record<string, any>; extensions: Record<string, any>;
coordinates: [number, number]; coordinates: Coordinates;
index: number; index: number;
} }
@@ -50,18 +48,19 @@ export class ElevationProfile {
private _chart: Chart | null = null; private _chart: Chart | null = null;
private _canvas: HTMLCanvasElement; private _canvas: HTMLCanvasElement;
private _overlay: HTMLCanvasElement; private _overlay: HTMLCanvasElement;
private _marker: mapboxgl.Marker | null = null;
private _dragging = false; private _dragging = false;
private _panning = false; private _panning = false;
private _gpxStatistics: Readable<GPXStatistics>; private _gpxStatistics: Readable<GPXStatisticsGroup>;
private _slicedGPXStatistics: Writable<[GPXStatistics, number, number] | undefined>; private _slicedGPXStatistics: Writable<[GPXGlobalStatistics, number, number] | undefined>;
private _hoveredPoint: Writable<Coordinates | null>;
private _additionalDatasets: Readable<string[]>; private _additionalDatasets: Readable<string[]>;
private _elevationFill: Readable<'slope' | 'surface' | 'highway' | undefined>; private _elevationFill: Readable<'slope' | 'surface' | 'highway' | undefined>;
constructor( constructor(
gpxStatistics: Readable<GPXStatistics>, gpxStatistics: Readable<GPXStatisticsGroup>,
slicedGPXStatistics: Writable<[GPXStatistics, number, number] | undefined>, slicedGPXStatistics: Writable<[GPXGlobalStatistics, number, number] | undefined>,
hoveredPoint: Writable<Coordinates | null>,
additionalDatasets: Readable<string[]>, additionalDatasets: Readable<string[]>,
elevationFill: Readable<'slope' | 'surface' | 'highway' | undefined>, elevationFill: Readable<'slope' | 'surface' | 'highway' | undefined>,
canvas: HTMLCanvasElement, canvas: HTMLCanvasElement,
@@ -69,17 +68,12 @@ export class ElevationProfile {
) { ) {
this._gpxStatistics = gpxStatistics; this._gpxStatistics = gpxStatistics;
this._slicedGPXStatistics = slicedGPXStatistics; this._slicedGPXStatistics = slicedGPXStatistics;
this._hoveredPoint = hoveredPoint;
this._additionalDatasets = additionalDatasets; this._additionalDatasets = additionalDatasets;
this._elevationFill = elevationFill; this._elevationFill = elevationFill;
this._canvas = canvas; this._canvas = canvas;
this._overlay = overlay; this._overlay = overlay;
let element = document.createElement('div');
element.className = 'h-4 w-4 rounded-full bg-cyan-500 border-2 border-white';
this._marker = new mapboxgl.Marker({
element,
});
import('chartjs-plugin-zoom').then((module) => { import('chartjs-plugin-zoom').then((module) => {
Chart.register(module.default); Chart.register(module.default);
this.initialize(); this.initialize();
@@ -162,14 +156,10 @@ export class ElevationProfile {
label: (context: TooltipItem<'line'>) => { label: (context: TooltipItem<'line'>) => {
let point = context.raw as ElevationProfilePoint; let point = context.raw as ElevationProfilePoint;
if (context.datasetIndex === 0) { if (context.datasetIndex === 0) {
const map_ = get(map); if (this._dragging) {
if (map_ && this._marker) { this._hoveredPoint.set(null);
if (this._dragging) { } else {
this._marker.remove(); this._hoveredPoint.set(point.coordinates);
} else {
this._marker.setLngLat(point.coordinates);
this._marker.addTo(map_);
}
} }
return `${i18n._('quantities.elevation')}: ${getElevationWithUnits(point.y, false)}`; return `${i18n._('quantities.elevation')}: ${getElevationWithUnits(point.y, false)}`;
} else if (context.datasetIndex === 1) { } else if (context.datasetIndex === 1) {
@@ -312,10 +302,7 @@ export class ElevationProfile {
events: ['mouseout'], events: ['mouseout'],
afterEvent: (chart: Chart, args: { event: ChartEvent }) => { afterEvent: (chart: Chart, args: { event: ChartEvent }) => {
if (args.event.type === 'mouseout') { if (args.event.type === 'mouseout') {
const map_ = get(map); this._hoveredPoint.set(null);
if (map_ && this._marker) {
this._marker.remove();
}
} }
}, },
}, },
@@ -342,7 +329,7 @@ export class ElevationProfile {
if (evt.x - rect.left <= this._chart.chartArea.left) { if (evt.x - rect.left <= this._chart.chartArea.left) {
return 0; return 0;
} else if (evt.x - rect.left >= this._chart.chartArea.right) { } else if (evt.x - rect.left >= this._chart.chartArea.right) {
return get(this._gpxStatistics).local.points.length - 1; return this._chart.data.datasets[0].data.length - 1;
} else { } else {
return undefined; return undefined;
} }
@@ -375,7 +362,7 @@ export class ElevationProfile {
startIndex = endIndex; startIndex = endIndex;
} else if (startIndex !== endIndex) { } else if (startIndex !== endIndex) {
this._slicedGPXStatistics.set([ this._slicedGPXStatistics.set([
get(this._gpxStatistics).slice( get(this._gpxStatistics).sliced(
Math.min(startIndex, endIndex), Math.min(startIndex, endIndex),
Math.max(startIndex, endIndex) Math.max(startIndex, endIndex)
), ),
@@ -405,100 +392,99 @@ export class ElevationProfile {
return; return;
} }
const data = get(this._gpxStatistics); const data = get(this._gpxStatistics);
const units = {
distance: get(distanceUnits),
velocity: get(velocityUnits),
temperature: get(temperatureUnits),
};
const datasets: Array<Array<any>> = [[], [], [], [], [], []];
data.forEachTrackPoint((trkpt, distance, speed, slope, index) => {
datasets[0].push({
x: getConvertedDistance(distance, units.distance),
y: trkpt.ele ? getConvertedElevation(trkpt.ele, units.distance) : 0,
time: trkpt.time,
slope: slope,
extensions: trkpt.getExtensions(),
coordinates: trkpt.getCoordinates(),
index: index,
});
if (data.global.time.total > 0) {
datasets[1].push({
x: getConvertedDistance(distance, units.distance),
y: getConvertedVelocity(speed, units.velocity, units.distance),
index: index,
});
}
if (data.global.hr.count > 0) {
datasets[2].push({
x: getConvertedDistance(distance, units.distance),
y: trkpt.getHeartRate(),
index: index,
});
}
if (data.global.cad.count > 0) {
datasets[3].push({
x: getConvertedDistance(distance, units.distance),
y: trkpt.getCadence(),
index: index,
});
}
if (data.global.atemp.count > 0) {
datasets[4].push({
x: getConvertedDistance(distance, units.distance),
y: getConvertedTemperature(trkpt.getTemperature(), units.temperature),
index: index,
});
}
if (data.global.power.count > 0) {
datasets[5].push({
x: getConvertedDistance(distance, units.distance),
y: trkpt.getPower(),
index: index,
});
}
});
this._chart.data.datasets[0] = { this._chart.data.datasets[0] = {
label: i18n._('quantities.elevation'), label: i18n._('quantities.elevation'),
data: data.local.points.map((point, index) => { data: datasets[0],
return {
x: getConvertedDistance(data.local.distance.total[index]),
y: point.ele ? getConvertedElevation(point.ele) : 0,
time: point.time,
slope: {
at: data.local.slope.at[index],
segment: data.local.slope.segment[index],
length: data.local.slope.length[index],
},
extensions: point.getExtensions(),
coordinates: point.getCoordinates(),
index: index,
};
}),
normalized: true, normalized: true,
fill: 'start', fill: 'start',
order: 1, order: 1,
segment: {}, segment: {},
}; };
this._chart.data.datasets[1] = { this._chart.data.datasets[1] = {
data: data: datasets[1],
data.global.time.total > 0
? data.local.points.map((point, index) => {
return {
x: getConvertedDistance(data.local.distance.total[index]),
y: getConvertedVelocity(data.local.speed[index]),
index: index,
};
})
: [],
normalized: true, normalized: true,
yAxisID: 'yspeed', yAxisID: 'yspeed',
}; };
this._chart.data.datasets[2] = { this._chart.data.datasets[2] = {
data: data: datasets[2],
data.global.hr.count > 0
? data.local.points.map((point, index) => {
return {
x: getConvertedDistance(data.local.distance.total[index]),
y: point.getHeartRate(),
index: index,
};
})
: [],
normalized: true, normalized: true,
yAxisID: 'yhr', yAxisID: 'yhr',
}; };
this._chart.data.datasets[3] = { this._chart.data.datasets[3] = {
data: data: datasets[3],
data.global.cad.count > 0
? data.local.points.map((point, index) => {
return {
x: getConvertedDistance(data.local.distance.total[index]),
y: point.getCadence(),
index: index,
};
})
: [],
normalized: true, normalized: true,
yAxisID: 'ycad', yAxisID: 'ycad',
}; };
this._chart.data.datasets[4] = { this._chart.data.datasets[4] = {
data: data: datasets[4],
data.global.atemp.count > 0
? data.local.points.map((point, index) => {
return {
x: getConvertedDistance(data.local.distance.total[index]),
y: getConvertedTemperature(point.getTemperature()),
index: index,
};
})
: [],
normalized: true, normalized: true,
yAxisID: 'yatemp', yAxisID: 'yatemp',
}; };
this._chart.data.datasets[5] = { this._chart.data.datasets[5] = {
data: data: datasets[5],
data.global.power.count > 0
? data.local.points.map((point, index) => {
return {
x: getConvertedDistance(data.local.distance.total[index]),
y: point.getPower(),
index: index,
};
})
: [],
normalized: true, normalized: true,
yAxisID: 'ypower', yAxisID: 'ypower',
}; };
this._chart.options.scales!.x!['min'] = 0; this._chart.options.scales!.x!['min'] = 0;
this._chart.options.scales!.x!['max'] = getConvertedDistance(data.global.distance.total); this._chart.options.scales!.x!['max'] = getConvertedDistance(
data.global.distance.total,
units.distance
);
this.setVisibility(); this.setVisibility();
this.setFill(); this.setFill();
@@ -591,10 +577,12 @@ export class ElevationProfile {
const gpxStatistics = get(this._gpxStatistics); const gpxStatistics = get(this._gpxStatistics);
let startPixel = this._chart.scales.x.getPixelForValue( let startPixel = this._chart.scales.x.getPixelForValue(
getConvertedDistance(gpxStatistics.local.distance.total[startIndex]) getConvertedDistance(
gpxStatistics.getTrackPoint(startIndex)?.distance.total ?? 0
)
); );
let endPixel = this._chart.scales.x.getPixelForValue( let endPixel = this._chart.scales.x.getPixelForValue(
getConvertedDistance(gpxStatistics.local.distance.total[endIndex]) getConvertedDistance(gpxStatistics.getTrackPoint(endIndex)?.distance.total ?? 0)
); );
selectionContext.fillRect( selectionContext.fillRect(
@@ -636,8 +624,5 @@ export class ElevationProfile {
this._chart.destroy(); this._chart.destroy();
this._chart = null; this._chart = null;
} }
if (this._marker) {
this._marker.remove();
}
} }
} }

View File

@@ -16,7 +16,7 @@
import { setMode } from 'mode-watcher'; import { setMode } from 'mode-watcher';
import { settings } from '$lib/logic/settings'; import { settings } from '$lib/logic/settings';
import { fileStateCollection } from '$lib/logic/file-state'; import { fileStateCollection } from '$lib/logic/file-state';
import { gpxStatistics, slicedGPXStatistics } from '$lib/logic/statistics'; import { gpxStatistics, hoveredPoint, slicedGPXStatistics } from '$lib/logic/statistics';
import { loadFile } from '$lib/logic/file-actions'; import { loadFile } from '$lib/logic/file-actions';
import { selection } from '$lib/logic/selection'; import { selection } from '$lib/logic/selection';
import { untrack } from 'svelte'; import { untrack } from 'svelte';
@@ -102,7 +102,7 @@
<div class="grow relative"> <div class="grow relative">
<Map <Map
class="h-full {$fileStateCollection.size > 1 ? 'horizontal' : ''}" class="h-full {$fileStateCollection.size > 1 ? 'horizontal' : ''}"
accessToken={options.token} maptilerKey={options.key}
geocoder={false} geocoder={false}
geolocate={true} geolocate={true}
hash={useHash} hash={useHash}
@@ -130,6 +130,7 @@
<ElevationProfile <ElevationProfile
{gpxStatistics} {gpxStatistics}
{slicedGPXStatistics} {slicedGPXStatistics}
{hoveredPoint}
{additionalDatasets} {additionalDatasets}
{elevationFill} {elevationFill}
showControls={options.elevation.controls} showControls={options.elevation.controls}

View File

@@ -22,7 +22,7 @@
getCleanedEmbeddingOptions, getCleanedEmbeddingOptions,
getMergedEmbeddingOptions, getMergedEmbeddingOptions,
} from './embedding'; } from './embedding';
import { PUBLIC_MAPBOX_TOKEN } from '$env/static/public'; import { PUBLIC_MAPTILER_KEY } from '$env/static/public';
import Embedding from './Embedding.svelte'; import Embedding from './Embedding.svelte';
import { onDestroy } from 'svelte'; import { onDestroy } from 'svelte';
import { base } from '$app/paths'; import { base } from '$app/paths';
@@ -32,7 +32,7 @@
let options = $state( let options = $state(
getMergedEmbeddingOptions( getMergedEmbeddingOptions(
{ {
token: 'YOUR_MAPBOX_TOKEN', key: 'YOUR_MAPTILER_KEY',
theme: mode.current, theme: mode.current,
}, },
defaultEmbeddingOptions defaultEmbeddingOptions
@@ -46,10 +46,10 @@
let iframeOptions = $derived( let iframeOptions = $derived(
getMergedEmbeddingOptions( getMergedEmbeddingOptions(
{ {
token: key:
options.token.length === 0 || options.token === 'YOUR_MAPBOX_TOKEN' options.key.length === 0 || options.key === 'YOUR_MAPTILER_KEY'
? PUBLIC_MAPBOX_TOKEN ? PUBLIC_MAPTILER_KEY
: options.token, : options.key,
files: files.split(',').filter((url) => url.length > 0), files: files.split(',').filter((url) => url.length > 0),
ids: driveIds.split(',').filter((id) => id.length > 0), ids: driveIds.split(',').filter((id) => id.length > 0),
elevation: { elevation: {
@@ -102,8 +102,8 @@
</Card.Header> </Card.Header>
<Card.Content> <Card.Content>
<fieldset class="flex flex-col gap-3"> <fieldset class="flex flex-col gap-3">
<Label for="token">{i18n._('embedding.mapbox_token')}</Label> <Label for="key">{i18n._('embedding.maptiler_key')}</Label>
<Input id="token" type="text" class="h-8" bind:value={options.token} /> <Input id="key" type="text" class="h-8" bind:value={options.key} />
<Label for="file_urls">{i18n._('embedding.file_urls')}</Label> <Label for="file_urls">{i18n._('embedding.file_urls')}</Label>
<Input id="file_urls" type="text" class="h-8" bind:value={files} /> <Input id="file_urls" type="text" class="h-8" bind:value={files} />
<Label for="drive_ids">{i18n._('embedding.drive_ids')}</Label> <Label for="drive_ids">{i18n._('embedding.drive_ids')}</Label>

View File

@@ -1,8 +1,8 @@
import { PUBLIC_MAPBOX_TOKEN } from '$env/static/public'; import { PUBLIC_MAPTILER_KEY } from '$env/static/public';
import { basemaps } from '$lib/assets/layers'; import { basemaps } from '$lib/assets/layers';
export type EmbeddingOptions = { export type EmbeddingOptions = {
token: string; key: string;
files: string[]; files: string[];
ids: string[]; ids: string[];
basemap: string; basemap: string;
@@ -26,10 +26,10 @@ export type EmbeddingOptions = {
}; };
export const defaultEmbeddingOptions = { export const defaultEmbeddingOptions = {
token: '', key: '',
files: [], files: [],
ids: [], ids: [],
basemap: 'mapboxOutdoors', basemap: 'maptilerTopo',
elevation: { elevation: {
show: true, show: true,
height: 170, height: 170,
@@ -107,7 +107,7 @@ export function getURLForGoogleDriveFile(fileId: string): string {
export function convertOldEmbeddingOptions(options: URLSearchParams): any { export function convertOldEmbeddingOptions(options: URLSearchParams): any {
let newOptions: any = { let newOptions: any = {
token: PUBLIC_MAPBOX_TOKEN, key: PUBLIC_MAPTILER_KEY,
files: [], files: [],
ids: [], ids: [],
}; };
@@ -123,7 +123,7 @@ export function convertOldEmbeddingOptions(options: URLSearchParams): any {
if (options.has('source')) { if (options.has('source')) {
let basemap = options.get('source')!; let basemap = options.get('source')!;
if (basemap === 'satellite') { if (basemap === 'satellite') {
newOptions.basemap = 'mapboxSatellite'; newOptions.basemap = 'maptilerSatellite';
} else if (basemap === 'otm') { } else if (basemap === 'otm') {
newOptions.basemap = 'openTopoMap'; newOptions.basemap = 'openTopoMap';
} else if (basemap === 'ohm') { } else if (basemap === 'ohm') {

View File

@@ -21,7 +21,7 @@
SquareActivity, SquareActivity,
} from '@lucide/svelte'; } from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte'; import { i18n } from '$lib/i18n.svelte';
import { GPXStatistics } from 'gpx'; import { GPXGlobalStatistics } from 'gpx';
import { ListRootItem } from '$lib/components/file-list/file-list'; import { ListRootItem } from '$lib/components/file-list/file-list';
import { fileStateCollection } from '$lib/logic/file-state'; import { fileStateCollection } from '$lib/logic/file-state';
import { selection } from '$lib/logic/selection'; import { selection } from '$lib/logic/selection';
@@ -48,24 +48,24 @@
extensions: false, extensions: false,
}; };
} else { } else {
let statistics = $gpxStatistics; let statistics = $gpxStatistics.global;
if (exportState.current === ExportState.ALL) { if (exportState.current === ExportState.ALL) {
statistics = Array.from(get(fileStateCollection).values()) statistics = Array.from(get(fileStateCollection).values())
.map((file) => file.statistics) .map((file) => file.statistics)
.reduce((acc, cur) => { .reduce((acc, cur) => {
if (cur !== undefined) { if (cur !== undefined) {
acc.mergeWith(cur.getStatisticsFor(new ListRootItem())); acc.mergeWith(cur.getStatisticsFor(new ListRootItem()).global);
} }
return acc; return acc;
}, new GPXStatistics()); }, new GPXGlobalStatistics());
} }
return { return {
time: statistics.global.time.total === 0, time: statistics.time.total === 0,
hr: statistics.global.hr.count === 0, hr: statistics.hr.count === 0,
cad: statistics.global.cad.count === 0, cad: statistics.cad.count === 0,
atemp: statistics.global.atemp.count === 0, atemp: statistics.atemp.count === 0,
power: statistics.global.power.count === 0, power: statistics.power.count === 0,
extensions: Object.keys(statistics.global.extensions).length === 0, extensions: Object.keys(statistics.extensions).length === 0,
}; };
} }
}); });

View File

@@ -34,11 +34,10 @@
import { editStyle } from '$lib/components/file-list/style/utils.svelte'; import { editStyle } from '$lib/components/file-list/style/utils.svelte';
import { getSymbolKey, symbols } from '$lib/assets/symbols'; import { getSymbolKey, symbols } from '$lib/assets/symbols';
import { selection, copied, cut } from '$lib/logic/selection'; import { selection, copied, cut } from '$lib/logic/selection';
import { map } from '$lib/components/map/map';
import { fileActions, pasteSelection } from '$lib/logic/file-actions'; import { fileActions, pasteSelection } from '$lib/logic/file-actions';
import { allHidden } from '$lib/logic/hidden'; import { allHidden } from '$lib/logic/hidden';
import { boundsManager } from '$lib/logic/bounds'; import { boundsManager } from '$lib/logic/bounds';
import { gpxLayers } from '$lib/components/map/gpx-layer/gpx-layers'; import { gpxColors, gpxLayers } from '$lib/components/map/gpx-layer/gpx-layers';
import { fileStateCollection } from '$lib/logic/file-state'; import { fileStateCollection } from '$lib/logic/file-state';
import { waypointPopup } from '$lib/components/map/gpx-layer/gpx-layer-popup'; import { waypointPopup } from '$lib/components/map/gpx-layer/gpx-layer-popup';
import { allowedPastes } from './sortable-file-list'; import { allowedPastes } from './sortable-file-list';
@@ -58,41 +57,31 @@
let singleSelection = $derived($selection.size === 1); let singleSelection = $derived($selection.size === 1);
let nodeColors: string[] = $state([]); let nodeColors: string[] = $derived.by(() => {
$effect.pre(() => {
let colors: string[] = []; let colors: string[] = [];
if (node && $map) { if (node) {
if (node instanceof GPXFile) { if (node instanceof GPXFile) {
let defaultColor = undefined; let defaultColor = $gpxColors.get(item.getFileId());
let layer = gpxLayers.getLayer(item.getFileId());
if (layer) {
defaultColor = layer.layerColor;
}
let style = node.getStyle(defaultColor); let style = node.getStyle(defaultColor);
style.color.forEach((c) => { colors = style.color;
if (!colors.includes(c)) {
colors.push(c);
}
});
} else if (node instanceof Track) { } else if (node instanceof Track) {
let style = node.getStyle(); let style = node.getStyle();
if (style) { if (
if (style['gpx_style:color'] && !colors.includes(style['gpx_style:color'])) { style &&
colors.push(style['gpx_style:color']); style['gpx_style:color'] &&
} !colors.includes(style['gpx_style:color'])
) {
colors.push(style['gpx_style:color']);
} }
if (colors.length === 0) { if (colors.length === 0) {
let layer = gpxLayers.getLayer(item.getFileId()); let defaultColor = $gpxColors.get(item.getFileId());
if (layer) { if (defaultColor) {
colors.push(layer.layerColor); colors.push(defaultColor);
} }
} }
} }
} }
nodeColors = colors; return colors;
}); });
let symbolKey = $derived(node instanceof Waypoint ? getSymbolKey(node.sym) : undefined); let symbolKey = $derived(node instanceof Waypoint ? getSymbolKey(node.sym) : undefined);

View File

@@ -1,30 +1,25 @@
<script lang="ts"> <script lang="ts">
import { onDestroy, onMount } from 'svelte'; import { onDestroy, onMount } from 'svelte';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import '@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css';
import { Button } from '$lib/components/ui/button'; import { Button } from '$lib/components/ui/button';
import { i18n } from '$lib/i18n.svelte'; import { i18n } from '$lib/i18n.svelte';
import { PUBLIC_MAPBOX_TOKEN } from '$env/static/public';
import { page } from '$app/state'; import { page } from '$app/state';
import { map } from '$lib/components/map/map'; import { map } from '$lib/components/map/map';
import { PUBLIC_MAPTILER_KEY } from '$env/static/public';
let { let {
accessToken = PUBLIC_MAPBOX_TOKEN, maptilerKey = PUBLIC_MAPTILER_KEY,
geolocate = true, geolocate = true,
geocoder = true, geocoder = true,
hash = true, hash = true,
class: className = '', class: className = '',
}: { }: {
accessToken?: string; maptilerKey?: string;
geolocate?: boolean; geolocate?: boolean;
geocoder?: boolean; geocoder?: boolean;
hash?: boolean; hash?: boolean;
class?: string; class?: string;
} = $props(); } = $props();
mapboxgl.accessToken = accessToken;
let webgl2Supported = $state(true); let webgl2Supported = $state(true);
let embeddedApp = $state(false); let embeddedApp = $state(false);
@@ -48,7 +43,7 @@
language = 'en'; language = 'en';
} }
map.init(PUBLIC_MAPBOX_TOKEN, language, hash, geocoder, geolocate); map.init(maptilerKey, language, hash, geocoder, geolocate);
}); });
onDestroy(() => { onDestroy(() => {
@@ -81,21 +76,21 @@
<style lang="postcss"> <style lang="postcss">
@reference "../../../app.css"; @reference "../../../app.css";
div :global(.mapboxgl-map) { div :global(.maplibregl-map) {
@apply font-sans; @apply font-sans;
} }
div :global(.mapboxgl-ctrl-top-right > .mapboxgl-ctrl) { div :global(.maplibregl-ctrl-top-right > .maplibregl-ctrl) {
@apply shadow-md; @apply shadow-md;
@apply bg-background; @apply bg-background;
@apply text-foreground; @apply text-foreground;
} }
div :global(.mapboxgl-ctrl-icon) { div :global(.maplibregl-ctrl-icon) {
@apply dark:brightness-[4.7]; @apply dark:brightness-[4.7];
} }
div :global(.mapboxgl-ctrl-geocoder) { div :global(.maplibregl-ctrl-geocoder) {
@apply flex; @apply flex;
@apply flex-row; @apply flex-row;
@apply w-fit; @apply w-fit;
@@ -110,27 +105,27 @@
@apply text-foreground; @apply text-foreground;
} }
div :global(.mapboxgl-ctrl-geocoder .suggestions > li > a) { div :global(.maplibregl-ctrl-geocoder .suggestions > li > a) {
@apply text-foreground; @apply text-foreground;
@apply hover:text-accent-foreground; @apply hover:text-accent-foreground;
@apply hover:bg-accent; @apply hover:bg-accent;
} }
div :global(.mapboxgl-ctrl-geocoder .suggestions > .active > a) { div :global(.maplibregl-ctrl-geocoder .suggestions > .active > a) {
@apply bg-background; @apply bg-background;
} }
div :global(.mapboxgl-ctrl-geocoder--button) { div :global(.maplibregl-ctrl-geocoder--button) {
@apply bg-transparent; @apply bg-transparent;
@apply hover:bg-transparent; @apply hover:bg-transparent;
} }
div :global(.mapboxgl-ctrl-geocoder--icon) { div :global(.maplibregl-ctrl-geocoder--icon) {
@apply fill-foreground; @apply fill-foreground;
@apply hover:fill-accent-foreground; @apply hover:fill-accent-foreground;
} }
div :global(.mapboxgl-ctrl-geocoder--icon-search) { div :global(.maplibregl-ctrl-geocoder--icon-search) {
@apply relative; @apply relative;
@apply top-0; @apply top-0;
@apply left-0; @apply left-0;
@@ -138,7 +133,7 @@
@apply w-[29px]; @apply w-[29px];
} }
div :global(.mapboxgl-ctrl-geocoder--input) { div :global(.maplibregl-ctrl-geocoder--input) {
@apply relative; @apply relative;
@apply w-64; @apply w-64;
@apply py-0; @apply py-0;
@@ -149,12 +144,12 @@
@apply text-foreground; @apply text-foreground;
} }
div :global(.mapboxgl-ctrl-geocoder--collapsed .mapboxgl-ctrl-geocoder--input) { div :global(.maplibregl-ctrl-geocoder--collapsed .maplibregl-ctrl-geocoder--input) {
@apply w-0; @apply w-0;
@apply p-0; @apply p-0;
} }
div :global(.mapboxgl-ctrl-top-right) { div :global(.maplibregl-ctrl-top-right) {
@apply z-40; @apply z-40;
@apply flex; @apply flex;
@apply flex-col; @apply flex-col;
@@ -163,77 +158,76 @@
@apply overflow-hidden; @apply overflow-hidden;
} }
.horizontal :global(.mapboxgl-ctrl-bottom-left) { .horizontal :global(.maplibregl-ctrl-bottom-left) {
@apply bottom-[42px]; @apply bottom-[42px];
} }
.horizontal :global(.mapboxgl-ctrl-bottom-right) { .horizontal :global(.maplibregl-ctrl-bottom-right) {
@apply bottom-[42px]; @apply bottom-[42px];
} }
div :global(.mapboxgl-ctrl-attrib) { div :global(.maplibregl-ctrl-attrib) {
@apply dark:bg-transparent; @apply dark:bg-transparent;
} }
div :global(.mapboxgl-compact-show.mapboxgl-ctrl-attrib) { div :global(.maplibregl-compact-show.maplibregl-ctrl-attrib) {
@apply dark:bg-background; @apply dark:bg-background;
} }
div :global(.mapboxgl-ctrl-attrib-button) { div :global(.maplibregl-ctrl-attrib-button) {
@apply dark:bg-foreground; @apply dark:bg-foreground;
} }
div :global(.mapboxgl-compact-show .mapboxgl-ctrl-attrib-button) { div :global(.maplibregl-compact-show .maplibregl-ctrl-attrib-button) {
@apply dark:bg-foreground; @apply dark:bg-foreground;
} }
div :global(.mapboxgl-ctrl-attrib a) { div :global(.maplibregl-ctrl-attrib a) {
@apply text-foreground; @apply text-foreground;
} }
div :global(.mapboxgl-popup) { div :global(.maplibregl-popup) {
@apply w-fit;
@apply z-50; @apply z-50;
} }
div :global(.mapboxgl-popup-content) { div :global(.maplibregl-popup-content) {
@apply p-0; @apply p-0;
@apply bg-transparent; @apply bg-transparent;
@apply shadow-none; @apply shadow-none;
} }
div :global(.mapboxgl-popup-anchor-top .mapboxgl-popup-tip) { div :global(.maplibregl-popup-anchor-top .maplibregl-popup-tip) {
@apply border-b-background; @apply border-b-background;
} }
div :global(.mapboxgl-popup-anchor-top-left .mapboxgl-popup-tip) { div :global(.maplibregl-popup-anchor-top-left .maplibregl-popup-tip) {
@apply border-b-background; @apply border-b-background;
} }
div :global(.mapboxgl-popup-anchor-top-right .mapboxgl-popup-tip) { div :global(.maplibregl-popup-anchor-top-right .maplibregl-popup-tip) {
@apply border-b-background; @apply border-b-background;
} }
div :global(.mapboxgl-popup-anchor-bottom .mapboxgl-popup-tip) { div :global(.maplibregl-popup-anchor-bottom .maplibregl-popup-tip) {
@apply border-t-background; @apply border-t-background;
@apply drop-shadow-md; @apply drop-shadow-md;
} }
div :global(.mapboxgl-popup-anchor-bottom-left .mapboxgl-popup-tip) { div :global(.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip) {
@apply border-t-background; @apply border-t-background;
@apply drop-shadow-md; @apply drop-shadow-md;
} }
div :global(.mapboxgl-popup-anchor-bottom-right .mapboxgl-popup-tip) { div :global(.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip) {
@apply border-t-background; @apply border-t-background;
@apply drop-shadow-md; @apply drop-shadow-md;
} }
div :global(.mapboxgl-popup-anchor-left .mapboxgl-popup-tip) { div :global(.maplibregl-popup-anchor-left .maplibregl-popup-tip) {
@apply border-r-background; @apply border-r-background;
} }
div :global(.mapboxgl-popup-anchor-right .mapboxgl-popup-tip) { div :global(.maplibregl-popup-anchor-right .maplibregl-popup-tip) {
@apply border-l-background; @apply border-l-background;
} }
</style> </style>

View File

@@ -17,7 +17,7 @@
let control: CustomControl | null = null; let control: CustomControl | null = null;
onMount(() => { onMount(() => {
map.onLoad((map: mapboxgl.Map) => { map.onLoad((map: maplibregl.Map) => {
if (position.includes('right')) container.classList.add('float-right'); if (position.includes('right')) container.classList.add('float-right');
else container.classList.add('float-left'); else container.classList.add('float-left');
container.classList.remove('hidden'); container.classList.remove('hidden');

View File

@@ -1,4 +1,4 @@
import { type Map, type IControl } from 'mapbox-gl'; import { type Map, type IControl } from 'maplibre-gl';
export default class CustomControl implements IControl { export default class CustomControl implements IControl {
_map: Map | undefined; _map: Map | undefined;

View File

@@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { onDestroy, onMount } from 'svelte'; import { onDestroy } from 'svelte';
import { gpxLayers } from '$lib/components/map/gpx-layer/gpx-layers'; import { gpxLayers } from '$lib/components/map/gpx-layer/gpx-layers';
import { DistanceMarkers } from '$lib/components/map/gpx-layer/distance-markers'; import { DistanceMarkers } from '$lib/components/map/gpx-layer/distance-markers';
import { StartEndMarkers } from '$lib/components/map/gpx-layer/start-end-markers'; import { StartEndMarkers } from '$lib/components/map/gpx-layer/start-end-markers';
@@ -9,13 +9,10 @@
let distanceMarkers: DistanceMarkers; let distanceMarkers: DistanceMarkers;
let startEndMarkers: StartEndMarkers; let startEndMarkers: StartEndMarkers;
onMount(() => { map.onLoad((map_) => {
gpxLayers.init(); gpxLayers.init();
startEndMarkers = new StartEndMarkers(); startEndMarkers = new StartEndMarkers();
distanceMarkers = new DistanceMarkers(); distanceMarkers = new DistanceMarkers();
});
map.onLoad((map_) => {
createPopups(map_); createPopups(map_);
}); });

View File

@@ -41,6 +41,7 @@
<Button <Button
size="sm" size="sm"
variant="outline" variant="outline"
class="justify-start"
href={`https://www.openstreetmap.org/edit?#map=${(($map?.getZoom() ?? 17) + 1).toFixed(0)}/${trackpoint.item.getLatitude().toFixed(5)}/${trackpoint.item.getLongitude().toFixed(5)}`} href={`https://www.openstreetmap.org/edit?#map=${(($map?.getZoom() ?? 17) + 1).toFixed(0)}/${trackpoint.item.getLatitude().toFixed(5)}/${trackpoint.item.getLongitude().toFixed(5)}`}
target="_blank" target="_blank"
> >

View File

@@ -1,10 +1,11 @@
import { settings } from '$lib/logic/settings'; import { settings } from '$lib/logic/settings';
import { gpxStatistics } from '$lib/logic/statistics'; import { gpxStatistics } from '$lib/logic/statistics';
import { getConvertedDistanceToKilometers } from '$lib/units'; import { getConvertedDistanceToKilometers } from '$lib/units';
import type { GeoJSONSource } from 'mapbox-gl';
import { get } from 'svelte/store'; import { get } from 'svelte/store';
import { map } from '$lib/components/map/map'; import { map } from '$lib/components/map/map';
import { allHidden } from '$lib/logic/hidden'; import { allHidden } from '$lib/logic/hidden';
import type { GeoJSONSource } from 'maplibre-gl';
import { ANCHOR_LAYER_KEY } from '../style';
const { distanceMarkers, distanceUnits } = settings; const { distanceMarkers, distanceUnits } = settings;
@@ -22,7 +23,7 @@ export class DistanceMarkers {
this.unsubscribes.push( this.unsubscribes.push(
map.subscribe((map_) => { map.subscribe((map_) => {
if (map_) { if (map_) {
map_.on('style.import.load', this.updateBinded); map_.on('style.load', this.updateBinded);
} }
}) })
); );
@@ -44,44 +45,45 @@ export class DistanceMarkers {
}); });
} }
if (!map_.getLayer('distance-markers')) { if (!map_.getLayer('distance-markers')) {
map_.addLayer({ map_.addLayer(
id: 'distance-markers', {
type: 'symbol', id: 'distance-markers',
source: 'distance-markers', type: 'symbol',
filter: [ source: 'distance-markers',
'match', filter: [
['get', 'level'], 'match',
100, ['get', 'level'],
['>=', ['zoom'], 0], 100,
50, ['>=', ['zoom'], 0],
['>=', ['zoom'], 7], 50,
25, ['>=', ['zoom'], 7],
[ 25,
'any', [
['all', ['>=', ['zoom'], 8], ['<=', ['zoom'], 9]], 'any',
['all', ['>=', ['zoom'], 8], ['<=', ['zoom'], 9]],
['>=', ['zoom'], 11],
],
10,
['>=', ['zoom'], 10],
5,
['>=', ['zoom'], 11], ['>=', ['zoom'], 11],
1,
['>=', ['zoom'], 13],
false,
], ],
10, layout: {
['>=', ['zoom'], 10], 'text-field': ['get', 'distance'],
5, 'text-size': 14,
['>=', ['zoom'], 11], 'text-font': ['Open Sans Bold'],
1, },
['>=', ['zoom'], 13], paint: {
false, 'text-color': 'black',
], 'text-halo-width': 2,
layout: { 'text-halo-color': 'white',
'text-field': ['get', 'distance'], },
'text-size': 14,
'text-font': ['Open Sans Bold'],
}, },
paint: { ANCHOR_LAYER_KEY.distanceMarkers
'text-color': 'black', );
'text-halo-width': 2,
'text-halo-color': 'white',
},
});
} else {
map_.moveLayer('distance-markers');
} }
} else { } else {
if (map_.getLayer('distance-markers')) { if (map_.getLayer('distance-markers')) {
@@ -101,23 +103,17 @@ export class DistanceMarkers {
getDistanceMarkersGeoJSON(): GeoJSON.FeatureCollection { getDistanceMarkersGeoJSON(): GeoJSON.FeatureCollection {
let statistics = get(gpxStatistics); let statistics = get(gpxStatistics);
let features = []; let features: GeoJSON.Feature[] = [];
let currentTargetDistance = 1; let currentTargetDistance = 1;
for (let i = 0; i < statistics.local.distance.total.length; i++) { statistics.forEachTrackPoint((trkpt, dist) => {
if ( if (dist >= getConvertedDistanceToKilometers(currentTargetDistance)) {
statistics.local.distance.total[i] >=
getConvertedDistanceToKilometers(currentTargetDistance)
) {
let distance = currentTargetDistance.toFixed(0); let distance = currentTargetDistance.toFixed(0);
let level = levels.find((level) => currentTargetDistance % level === 0) || 1; let level = levels.find((level) => currentTargetDistance % level === 0) || 1;
features.push({ features.push({
type: 'Feature', type: 'Feature',
geometry: { geometry: {
type: 'Point', type: 'Point',
coordinates: [ coordinates: [trkpt.getLongitude(), trkpt.getLatitude()],
statistics.local.points[i].getLongitude(),
statistics.local.points[i].getLatitude(),
],
}, },
properties: { properties: {
distance, distance,
@@ -126,7 +122,7 @@ export class DistanceMarkers {
} as GeoJSON.Feature); } as GeoJSON.Feature);
currentTargetDistance += 1; currentTargetDistance += 1;
} }
} });
return { return {
type: 'FeatureCollection', type: 'FeatureCollection',

View File

@@ -3,13 +3,14 @@ import { MapPopup } from '$lib/components/map/map-popup';
export let waypointPopup: MapPopup | null = null; export let waypointPopup: MapPopup | null = null;
export let trackpointPopup: MapPopup | null = null; export let trackpointPopup: MapPopup | null = null;
export function createPopups(map: mapboxgl.Map) { export function createPopups(map: maplibregl.Map) {
removePopups(); removePopups();
waypointPopup = new MapPopup(map, { waypointPopup = new MapPopup(map, {
closeButton: false, closeButton: false,
focusAfterOpen: false, focusAfterOpen: false,
maxWidth: undefined, maxWidth: undefined,
offset: { offset: {
center: [0, 0],
top: [0, 0], top: [0, 0],
'top-left': [0, 0], 'top-left': [0, 0],
'top-right': [0, 0], 'top-right': [0, 0],

View File

@@ -1,5 +1,10 @@
import { get, type Readable } from 'svelte/store'; import { get, type Readable } from 'svelte/store';
import mapboxgl, { type FilterSpecification } from 'mapbox-gl'; import maplibregl, {
type GeoJSONSource,
type FilterSpecification,
type MapLayerMouseEvent,
type MapLayerTouchEvent,
} from 'maplibre-gl';
import { map } from '$lib/components/map/map'; import { map } from '$lib/components/map/map';
import { waypointPopup, trackpointPopup } from './gpx-layer-popup'; import { waypointPopup, trackpointPopup } from './gpx-layer-popup';
import { import {
@@ -10,7 +15,7 @@ import {
ListFileItem, ListFileItem,
ListRootItem, ListRootItem,
} from '$lib/components/file-list/file-list'; } from '$lib/components/file-list/file-list';
import { getClosestLinePoint, getElevation } from '$lib/utils'; import { getClosestLinePoint, getElevation, loadSVGIcon } from '$lib/utils';
import { selectedWaypoint } from '$lib/components/toolbar/tools/waypoint/waypoint'; import { selectedWaypoint } from '$lib/components/toolbar/tools/waypoint/waypoint';
import { MapPin, Square } from 'lucide-static'; import { MapPin, Square } from 'lucide-static';
import { getSymbolKey, symbols } from '$lib/assets/symbols'; import { getSymbolKey, symbols } from '$lib/assets/symbols';
@@ -22,6 +27,8 @@ import { fileActionManager } from '$lib/logic/file-action-manager';
import { fileActions } from '$lib/logic/file-actions'; import { fileActions } from '$lib/logic/file-actions';
import { splitAs } from '$lib/components/toolbar/tools/scissors/scissors'; import { splitAs } from '$lib/components/toolbar/tools/scissors/scissors';
import { mapCursor, MapCursorState } from '$lib/logic/map-cursor'; import { mapCursor, MapCursorState } from '$lib/logic/map-cursor';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
import { gpxColors } from './gpx-layers';
const colors = [ const colors = [
'#ff0000', '#ff0000',
@@ -43,16 +50,35 @@ for (let color of colors) {
} }
// Get the color with the least amount of uses // Get the color with the least amount of uses
function getColor() { function getColor(fileId: string) {
let color = colors.reduce((a, b) => (colorCount[a] <= colorCount[b] ? a : b)); let color = colors.reduce((a, b) => (colorCount[a] <= colorCount[b] ? a : b));
colorCount[color]++; colorCount[color]++;
gpxColors.update((colors) => {
colors.set(fileId, color);
return colors;
});
return color; return color;
} }
function decrementColor(color: string) { function replaceColor(fileId: string, oldColor: string, newColor: string) {
if (colorCount.hasOwnProperty(oldColor)) {
colorCount[oldColor]--;
}
colorCount[newColor]++;
gpxColors.update((colors) => {
colors.set(fileId, newColor);
return colors;
});
}
function removeColor(fileId: string, color: string) {
if (colorCount.hasOwnProperty(color)) { if (colorCount.hasOwnProperty(color)) {
colorCount[color]--; colorCount[color]--;
} }
gpxColors.update((colors) => {
colors.delete(fileId);
return colors;
});
} }
export function getSvgForSymbol(symbol?: string | undefined, layerColor?: string | undefined) { export function getSvgForSymbol(symbol?: string | undefined, layerColor?: string | undefined) {
@@ -94,38 +120,38 @@ export class GPXLayer {
selected: boolean = false; selected: boolean = false;
currentWaypointData: GeoJSON.FeatureCollection | null = null; currentWaypointData: GeoJSON.FeatureCollection | null = null;
draggedWaypointIndex: number | null = null; draggedWaypointIndex: number | null = null;
draggingStartingPosition: mapboxgl.Point = new mapboxgl.Point(0, 0); draggingStartingPosition: maplibregl.Point = new maplibregl.Point(0, 0);
unsubscribe: Function[] = []; unsubscribe: Function[] = [];
updateBinded: () => void = this.update.bind(this); updateBinded: () => void = this.update.bind(this);
layerOnMouseEnterBinded: (e: any) => void = this.layerOnMouseEnter.bind(this); layerOnMouseEnterBinded: (e: any) => void = this.layerOnMouseEnter.bind(this);
layerOnMouseLeaveBinded: () => void = this.layerOnMouseLeave.bind(this); layerOnMouseLeaveBinded: () => void = this.layerOnMouseLeave.bind(this);
layerOnMouseMoveBinded: (e: any) => void = this.layerOnMouseMove.bind(this); layerOnMouseMoveBinded: (e: any) => void = this.layerOnMouseMove.bind(this);
layerOnClickBinded: (e: any) => void = this.layerOnClick.bind(this); layerOnClickBinded: (e: MapLayerMouseEvent) => void = this.layerOnClick.bind(this);
layerOnContextMenuBinded: (e: any) => void = this.layerOnContextMenu.bind(this); layerOnContextMenuBinded: (e: MapLayerMouseEvent) => void = this.layerOnContextMenu.bind(this);
waypointLayerOnMouseEnterBinded: (e: mapboxgl.MapMouseEvent) => void = waypointLayerOnMouseEnterBinded: (e: MapLayerMouseEvent) => void =
this.waypointLayerOnMouseEnter.bind(this); this.waypointLayerOnMouseEnter.bind(this);
waypointLayerOnMouseLeaveBinded: (e: mapboxgl.MapMouseEvent) => void = waypointLayerOnMouseLeaveBinded: (e: MapLayerMouseEvent) => void =
this.waypointLayerOnMouseLeave.bind(this); this.waypointLayerOnMouseLeave.bind(this);
waypointLayerOnClickBinded: (e: mapboxgl.MapMouseEvent) => void = waypointLayerOnClickBinded: (e: MapLayerMouseEvent) => void =
this.waypointLayerOnClick.bind(this); this.waypointLayerOnClick.bind(this);
waypointLayerOnMouseDownBinded: (e: mapboxgl.MapMouseEvent) => void = waypointLayerOnMouseDownBinded: (e: MapLayerMouseEvent) => void =
this.waypointLayerOnMouseDown.bind(this); this.waypointLayerOnMouseDown.bind(this);
waypointLayerOnTouchStartBinded: (e: mapboxgl.MapTouchEvent) => void = waypointLayerOnTouchStartBinded: (e: MapLayerTouchEvent) => void =
this.waypointLayerOnTouchStart.bind(this); this.waypointLayerOnTouchStart.bind(this);
waypointLayerOnMouseMoveBinded: (e: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent) => void = waypointLayerOnMouseMoveBinded: (e: MapLayerMouseEvent | MapLayerTouchEvent) => void =
this.waypointLayerOnMouseMove.bind(this); this.waypointLayerOnMouseMove.bind(this);
waypointLayerOnMouseUpBinded: (e: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent) => void = waypointLayerOnMouseUpBinded: (e: MapLayerMouseEvent | MapLayerTouchEvent) => void =
this.waypointLayerOnMouseUp.bind(this); this.waypointLayerOnMouseUp.bind(this);
constructor(fileId: string, file: Readable<GPXFileWithStatistics | undefined>) { constructor(fileId: string, file: Readable<GPXFileWithStatistics | undefined>) {
this.fileId = fileId; this.fileId = fileId;
this.file = file; this.file = file;
this.layerColor = getColor(); this.layerColor = getColor(fileId);
this.unsubscribe.push( this.unsubscribe.push(
map.subscribe(($map) => { map.subscribe(($map) => {
if ($map) { if ($map) {
$map.on('style.import.load', this.updateBinded); $map.on('style.load', this.updateBinded);
this.update(); this.update();
} }
}) })
@@ -148,8 +174,9 @@ export class GPXLayer {
update() { update() {
const _map = get(map); const _map = get(map);
const layerEventManager = map.layerEventManager;
let file = get(this.file)?.file; let file = get(this.file)?.file;
if (!_map || !file) { if (!_map || !layerEventManager || !file) {
return; return;
} }
@@ -158,14 +185,14 @@ export class GPXLayer {
file._data.style.color && file._data.style.color &&
this.layerColor !== `#${file._data.style.color}` this.layerColor !== `#${file._data.style.color}`
) { ) {
decrementColor(this.layerColor); replaceColor(this.fileId, this.layerColor, `#${file._data.style.color}`);
this.layerColor = `#${file._data.style.color}`; this.layerColor = `#${file._data.style.color}`;
} }
this.loadIcons(); this.loadIcons();
try { try {
let source = _map.getSource(this.fileId) as mapboxgl.GeoJSONSource | undefined; let source = _map.getSource(this.fileId) as GeoJSONSource | undefined;
if (source) { if (source) {
source.setData(this.getGeoJSON()); source.setData(this.getGeoJSON());
} else { } else {
@@ -176,77 +203,44 @@ export class GPXLayer {
} }
if (!_map.getLayer(this.fileId)) { if (!_map.getLayer(this.fileId)) {
_map.addLayer({ _map.addLayer(
id: this.fileId, {
type: 'line', id: this.fileId,
source: this.fileId, type: 'line',
layout: { source: this.fileId,
'line-join': 'round', layout: {
'line-cap': 'round', 'line-join': 'round',
'line-cap': 'round',
},
paint: {
'line-color': ['get', 'color'],
'line-width': ['get', 'width'],
'line-opacity': ['get', 'opacity'],
},
}, },
paint: { ANCHOR_LAYER_KEY.tracks
'line-color': ['get', 'color'], );
'line-width': ['get', 'width'],
'line-opacity': ['get', 'opacity'],
},
});
_map.on('click', this.fileId, this.layerOnClickBinded); layerEventManager.on('click', this.fileId, this.layerOnClickBinded);
_map.on('contextmenu', this.fileId, this.layerOnContextMenuBinded); layerEventManager.on('contextmenu', this.fileId, this.layerOnContextMenuBinded);
_map.on('mouseenter', this.fileId, this.layerOnMouseEnterBinded); layerEventManager.on('mouseenter', this.fileId, this.layerOnMouseEnterBinded);
_map.on('mouseleave', this.fileId, this.layerOnMouseLeaveBinded); layerEventManager.on('mouseleave', this.fileId, this.layerOnMouseLeaveBinded);
_map.on('mousemove', this.fileId, this.layerOnMouseMoveBinded); layerEventManager.on('mousemove', this.fileId, this.layerOnMouseMoveBinded);
} }
let waypointSource = _map.getSource(this.fileId + '-waypoints') as let visibleTrackSegmentIds: string[] = [];
| mapboxgl.GeoJSONSource file.forEachSegment((segment, trackIndex, segmentIndex) => {
| undefined; if (!segment._data.hidden) {
this.currentWaypointData = this.getWaypointsGeoJSON(); visibleTrackSegmentIds.push(`${trackIndex}-${segmentIndex}`);
if (waypointSource) { }
waypointSource.setData(this.currentWaypointData); });
} else { const segmentFilter: FilterSpecification = [
_map.addSource(this.fileId + '-waypoints', { 'in',
type: 'geojson', ['get', 'trackSegmentId'],
data: this.currentWaypointData, ['literal', visibleTrackSegmentIds],
}); ];
}
if (!_map.getLayer(this.fileId + '-waypoints')) { _map.setFilter(this.fileId, segmentFilter, { validate: false });
_map.addLayer({
id: this.fileId + '-waypoints',
type: 'symbol',
source: this.fileId + '-waypoints',
layout: {
'icon-image': ['get', 'icon'],
'icon-size': 0.3,
'icon-anchor': 'bottom',
'icon-padding': 0,
'icon-allow-overlap': true,
},
});
_map.on(
'mouseenter',
this.fileId + '-waypoints',
this.waypointLayerOnMouseEnterBinded
);
_map.on(
'mouseleave',
this.fileId + '-waypoints',
this.waypointLayerOnMouseLeaveBinded
);
_map.on('click', this.fileId + '-waypoints', this.waypointLayerOnClickBinded);
_map.on(
'mousedown',
this.fileId + '-waypoints',
this.waypointLayerOnMouseDownBinded
);
_map.on(
'touchstart',
this.fileId + '-waypoints',
this.waypointLayerOnTouchStartBinded
);
}
if (get(directionMarkers)) { if (get(directionMarkers)) {
if (!_map.getLayer(this.fileId + '-direction')) { if (!_map.getLayer(this.fileId + '-direction')) {
@@ -272,31 +266,72 @@ export class GPXLayer {
'text-halo-color': 'white', 'text-halo-color': 'white',
}, },
}, },
_map.getLayer('distance-markers') ? 'distance-markers' : undefined ANCHOR_LAYER_KEY.directionMarkers
); );
} }
_map.setFilter(this.fileId + '-direction', segmentFilter, { validate: false });
} else { } else {
if (_map.getLayer(this.fileId + '-direction')) { if (_map.getLayer(this.fileId + '-direction')) {
_map.removeLayer(this.fileId + '-direction'); _map.removeLayer(this.fileId + '-direction');
} }
} }
let visibleTrackSegmentIds: string[] = []; let waypointSource = _map.getSource(this.fileId + '-waypoints') as
file.forEachSegment((segment, trackIndex, segmentIndex) => { | GeoJSONSource
if (!segment._data.hidden) { | undefined;
visibleTrackSegmentIds.push(`${trackIndex}-${segmentIndex}`); this.currentWaypointData = this.getWaypointsGeoJSON();
} if (waypointSource) {
}); waypointSource.setData(this.currentWaypointData);
const segmentFilter: FilterSpecification = [ } else {
'in', _map.addSource(this.fileId + '-waypoints', {
['get', 'trackSegmentId'], type: 'geojson',
['literal', visibleTrackSegmentIds], data: this.currentWaypointData,
]; });
}
_map.setFilter(this.fileId, segmentFilter, { validate: false }); if (!_map.getLayer(this.fileId + '-waypoints')) {
_map.addLayer(
{
id: this.fileId + '-waypoints',
type: 'symbol',
source: this.fileId + '-waypoints',
layout: {
'icon-image': ['get', 'icon'],
'icon-size': 0.3,
'icon-anchor': 'bottom',
'icon-padding': 0,
'icon-allow-overlap': true,
},
},
ANCHOR_LAYER_KEY.waypoints
);
if (_map.getLayer(this.fileId + '-direction')) { layerEventManager.on(
_map.setFilter(this.fileId + '-direction', segmentFilter, { validate: false }); 'mouseenter',
this.fileId + '-waypoints',
this.waypointLayerOnMouseEnterBinded
);
layerEventManager.on(
'mouseleave',
this.fileId + '-waypoints',
this.waypointLayerOnMouseLeaveBinded
);
layerEventManager.on(
'click',
this.fileId + '-waypoints',
this.waypointLayerOnClickBinded
);
layerEventManager.on(
'mousedown',
this.fileId + '-waypoints',
this.waypointLayerOnMouseDownBinded
);
layerEventManager.on(
'touchstart',
this.fileId + '-waypoints',
this.waypointLayerOnTouchStartBinded
);
} }
let visibleWaypoints: number[] = []; let visibleWaypoints: number[] = [];
@@ -319,32 +354,47 @@ export class GPXLayer {
remove() { remove() {
const _map = get(map); const _map = get(map);
if (_map) {
_map.off('click', this.fileId, this.layerOnClickBinded);
_map.off('contextmenu', this.fileId, this.layerOnContextMenuBinded);
_map.off('mouseenter', this.fileId, this.layerOnMouseEnterBinded);
_map.off('mouseleave', this.fileId, this.layerOnMouseLeaveBinded);
_map.off('mousemove', this.fileId, this.layerOnMouseMoveBinded);
_map.off('style.import.load', this.updateBinded);
_map.off( if (_map) {
_map.off('style.load', this.updateBinded);
}
const layerEventManager = map.layerEventManager;
if (layerEventManager) {
layerEventManager.off('click', this.fileId, this.layerOnClickBinded);
layerEventManager.off('contextmenu', this.fileId, this.layerOnContextMenuBinded);
layerEventManager.off('mouseenter', this.fileId, this.layerOnMouseEnterBinded);
layerEventManager.off('mouseleave', this.fileId, this.layerOnMouseLeaveBinded);
layerEventManager.off('mousemove', this.fileId, this.layerOnMouseMoveBinded);
layerEventManager.off(
'mouseenter', 'mouseenter',
this.fileId + '-waypoints', this.fileId + '-waypoints',
this.waypointLayerOnMouseEnterBinded this.waypointLayerOnMouseEnterBinded
); );
_map.off( layerEventManager.off(
'mouseleave', 'mouseleave',
this.fileId + '-waypoints', this.fileId + '-waypoints',
this.waypointLayerOnMouseLeaveBinded this.waypointLayerOnMouseLeaveBinded
); );
_map.off('click', this.fileId + '-waypoints', this.waypointLayerOnClickBinded); layerEventManager.off(
_map.off('mousedown', this.fileId + '-waypoints', this.waypointLayerOnMouseDownBinded); 'click',
_map.off( this.fileId + '-waypoints',
this.waypointLayerOnClickBinded
);
layerEventManager.off(
'mousedown',
this.fileId + '-waypoints',
this.waypointLayerOnMouseDownBinded
);
layerEventManager.off(
'touchstart', 'touchstart',
this.fileId + '-waypoints', this.fileId + '-waypoints',
this.waypointLayerOnTouchStartBinded this.waypointLayerOnTouchStartBinded
); );
}
if (_map) {
if (_map.getLayer(this.fileId + '-direction')) { if (_map.getLayer(this.fileId + '-direction')) {
_map.removeLayer(this.fileId + '-direction'); _map.removeLayer(this.fileId + '-direction');
} }
@@ -364,7 +414,7 @@ export class GPXLayer {
this.unsubscribe.forEach((unsubscribe) => unsubscribe()); this.unsubscribe.forEach((unsubscribe) => unsubscribe());
decrementColor(this.layerColor); removeColor(this.fileId, this.layerColor);
} }
moveToFront() { moveToFront() {
@@ -373,13 +423,13 @@ export class GPXLayer {
return; return;
} }
if (_map.getLayer(this.fileId)) { if (_map.getLayer(this.fileId)) {
_map.moveLayer(this.fileId); _map.moveLayer(this.fileId, ANCHOR_LAYER_KEY.tracks);
} }
if (_map.getLayer(this.fileId + '-waypoints')) { if (_map.getLayer(this.fileId + '-waypoints')) {
_map.moveLayer(this.fileId + '-waypoints'); _map.moveLayer(this.fileId + '-waypoints', ANCHOR_LAYER_KEY.waypoints);
} }
if (_map.getLayer(this.fileId + '-direction')) { if (_map.getLayer(this.fileId + '-direction')) {
_map.moveLayer(this.fileId + '-direction'); _map.moveLayer(this.fileId + '-direction', ANCHOR_LAYER_KEY.directionMarkers);
} }
} }
@@ -420,7 +470,7 @@ export class GPXLayer {
} }
} }
layerOnClick(e: mapboxgl.MapMouseEvent) { layerOnClick(e: MapLayerMouseEvent) {
if ( if (
get(currentTool) === Tool.ROUTING && get(currentTool) === Tool.ROUTING &&
get(selection).hasAnyChildren(new ListRootItem(), true, ['waypoints']) get(selection).hasAnyChildren(new ListRootItem(), true, ['waypoints'])
@@ -478,7 +528,7 @@ export class GPXLayer {
} }
} }
waypointLayerOnMouseEnter(e: mapboxgl.MapMouseEvent) { waypointLayerOnMouseEnter(e: MapLayerMouseEvent) {
if (this.draggedWaypointIndex !== null) { if (this.draggedWaypointIndex !== null) {
return; return;
} }
@@ -498,7 +548,7 @@ export class GPXLayer {
mapCursor.notify(MapCursorState.WAYPOINT_HOVER, false); mapCursor.notify(MapCursorState.WAYPOINT_HOVER, false);
} }
waypointLayerOnClick(e: mapboxgl.MapMouseEvent) { waypointLayerOnClick(e: MapLayerMouseEvent) {
e.preventDefault(); e.preventDefault();
let waypointIndex = e.features![0].properties!.waypointIndex; let waypointIndex = e.features![0].properties!.waypointIndex;
@@ -540,7 +590,7 @@ export class GPXLayer {
} }
} }
waypointLayerOnMouseDown(e: mapboxgl.MapMouseEvent) { waypointLayerOnMouseDown(e: MapLayerMouseEvent) {
if (get(currentTool) !== Tool.WAYPOINT || !this.selected) { if (get(currentTool) !== Tool.WAYPOINT || !this.selected) {
return; return;
} }
@@ -550,6 +600,7 @@ export class GPXLayer {
} }
e.preventDefault(); e.preventDefault();
_map.dragPan.disable();
this.draggedWaypointIndex = e.features![0].properties!.waypointIndex; this.draggedWaypointIndex = e.features![0].properties!.waypointIndex;
this.draggingStartingPosition = e.point; this.draggingStartingPosition = e.point;
@@ -559,7 +610,7 @@ export class GPXLayer {
_map.once('mouseup', this.waypointLayerOnMouseUpBinded); _map.once('mouseup', this.waypointLayerOnMouseUpBinded);
} }
waypointLayerOnTouchStart(e: mapboxgl.MapTouchEvent) { waypointLayerOnTouchStart(e: MapLayerTouchEvent) {
if (e.points.length !== 1 || get(currentTool) !== Tool.WAYPOINT || !this.selected) { if (e.points.length !== 1 || get(currentTool) !== Tool.WAYPOINT || !this.selected) {
return; return;
} }
@@ -573,12 +624,13 @@ export class GPXLayer {
waypointPopup?.hide(); waypointPopup?.hide();
e.preventDefault(); e.preventDefault();
_map.dragPan.disable();
_map.on('touchmove', this.waypointLayerOnMouseMoveBinded); _map.on('touchmove', this.waypointLayerOnMouseMoveBinded);
_map.once('touchend', this.waypointLayerOnMouseUpBinded); _map.once('touchend', this.waypointLayerOnMouseUpBinded);
} }
waypointLayerOnMouseMove(e: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent) { waypointLayerOnMouseMove(e: MapLayerMouseEvent | MapLayerTouchEvent) {
if (this.draggedWaypointIndex === null || e.point.equals(this.draggingStartingPosition)) { if (this.draggedWaypointIndex === null || e.point.equals(this.draggingStartingPosition)) {
return; return;
} }
@@ -590,18 +642,25 @@ export class GPXLayer {
).coordinates = [e.lngLat.lng, e.lngLat.lat]; ).coordinates = [e.lngLat.lng, e.lngLat.lat];
let waypointSource = get(map)?.getSource(this.fileId + '-waypoints') as let waypointSource = get(map)?.getSource(this.fileId + '-waypoints') as
| mapboxgl.GeoJSONSource | GeoJSONSource
| undefined; | undefined;
if (waypointSource) { if (waypointSource) {
waypointSource.setData(this.currentWaypointData!); waypointSource.setData(this.currentWaypointData!);
} }
} }
waypointLayerOnMouseUp(e: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent) { waypointLayerOnMouseUp(e: MapLayerMouseEvent | MapLayerTouchEvent) {
mapCursor.notify(MapCursorState.WAYPOINT_DRAGGING, false); mapCursor.notify(MapCursorState.WAYPOINT_DRAGGING, false);
get(map)?.off('mousemove', this.waypointLayerOnMouseMoveBinded); const _map = get(map);
get(map)?.off('touchmove', this.waypointLayerOnMouseMoveBinded); if (!_map) {
return;
}
_map.dragPan.enable();
_map.off('mousemove', this.waypointLayerOnMouseMoveBinded);
_map.off('touchmove', this.waypointLayerOnMouseMoveBinded);
if (this.draggedWaypointIndex === null) { if (this.draggedWaypointIndex === null) {
return; return;
@@ -724,20 +783,7 @@ export class GPXLayer {
symbols.forEach((symbol) => { symbols.forEach((symbol) => {
const iconId = `waypoint-${symbol ?? 'default'}-${this.layerColor}`; const iconId = `waypoint-${symbol ?? 'default'}-${this.layerColor}`;
if (!_map.hasImage(iconId)) { loadSVGIcon(_map, iconId, getSvgForSymbol(symbol, this.layerColor));
let icon = new Image(100, 100);
icon.onload = () => {
if (!_map.hasImage(iconId)) {
_map.addImage(iconId, icon);
}
};
// Lucide icons are SVG files with a 24x24 viewBox
// Create a new SVG with a 32x32 viewBox and center the icon in a circle
icon.src =
'data:image/svg+xml,' +
encodeURIComponent(getSvgForSymbol(symbol, this.layerColor));
}
}); });
} }
} }

View File

@@ -1,4 +1,5 @@
import { GPXFileStateCollectionObserver } from '$lib/logic/file-state'; import { GPXFileStateCollectionObserver } from '$lib/logic/file-state';
import { writable } from 'svelte/store';
import { GPXLayer } from './gpx-layer'; import { GPXLayer } from './gpx-layer';
export class GPXLayerCollection { export class GPXLayerCollection {
@@ -42,3 +43,4 @@ export class GPXLayerCollection {
} }
export const gpxLayers = new GPXLayerCollection(); export const gpxLayers = new GPXLayerCollection();
export const gpxColors = writable(new Map<string, string>());

View File

@@ -1,30 +1,40 @@
import { currentTool, Tool } from '$lib/components/toolbar/tools'; import { currentTool, Tool } from '$lib/components/toolbar/tools';
import { gpxStatistics, slicedGPXStatistics } from '$lib/logic/statistics'; import { gpxStatistics, hoveredPoint, slicedGPXStatistics } from '$lib/logic/statistics';
import mapboxgl from 'mapbox-gl'; import type { GeoJSONSource } from 'maplibre-gl';
import { get } from 'svelte/store'; import { get } from 'svelte/store';
import { map } from '$lib/components/map/map'; import { map } from '$lib/components/map/map';
import { allHidden } from '$lib/logic/hidden'; import { allHidden } from '$lib/logic/hidden';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
import { loadSVGIcon } from '$lib/utils';
const startMarkerSVG = `<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
<circle cx="8" cy="8" r="6" fill="#22c55e" stroke="white" stroke-width="1.5"/>
</svg>`;
const endMarkerSVG = `<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="checkerboard" x="0" y="0" width="5" height="5" patternUnits="userSpaceOnUse">
<rect x="0" y="0" width="2.5" height="2.5" fill="white"/>
<rect x="2.5" y="2.5" width="2.5" height="2.5" fill="white"/>
<rect x="2.5" y="0" width="2.5" height="2.5" fill="black"/>
<rect x="0" y="2.5" width="2.5" height="2.5" fill="black"/>
</pattern>
</defs>
<circle cx="8" cy="8" r="6" fill="url(#checkerboard)" stroke="white" stroke-width="1.5"/>
</svg>`;
const hoverMarkerSVG = `<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
<circle cx="8" cy="8" r="6" fill="#00b8db" stroke="white" stroke-width="1.5"/>
</svg>`;
export class StartEndMarkers { export class StartEndMarkers {
start: mapboxgl.Marker;
end: mapboxgl.Marker;
updateBinded: () => void = this.update.bind(this); updateBinded: () => void = this.update.bind(this);
unsubscribes: (() => void)[] = []; unsubscribes: (() => void)[] = [];
constructor() { constructor() {
let startElement = document.createElement('div');
let endElement = document.createElement('div');
startElement.className = `h-4 w-4 rounded-full bg-green-500 border-2 border-white`;
endElement.className = `h-4 w-4 rounded-full border-2 border-white`;
endElement.style.background =
'repeating-conic-gradient(#fff 0 90deg, #000 0 180deg) 0 0/8px 8px round';
this.start = new mapboxgl.Marker({ element: startElement });
this.end = new mapboxgl.Marker({ element: endElement });
map.onLoad(() => this.update()); map.onLoad(() => this.update());
this.unsubscribes.push(gpxStatistics.subscribe(this.updateBinded)); this.unsubscribes.push(gpxStatistics.subscribe(this.updateBinded));
this.unsubscribes.push(slicedGPXStatistics.subscribe(this.updateBinded)); this.unsubscribes.push(slicedGPXStatistics.subscribe(this.updateBinded));
this.unsubscribes.push(hoveredPoint.subscribe(this.updateBinded));
this.unsubscribes.push(currentTool.subscribe(this.updateBinded)); this.unsubscribes.push(currentTool.subscribe(this.updateBinded));
this.unsubscribes.push(allHidden.subscribe(this.updateBinded)); this.unsubscribes.push(allHidden.subscribe(this.updateBinded));
} }
@@ -33,26 +43,113 @@ export class StartEndMarkers {
const map_ = get(map); const map_ = get(map);
if (!map_) return; if (!map_) return;
this.loadIcons();
const tool = get(currentTool); const tool = get(currentTool);
const statistics = get(slicedGPXStatistics)?.[0] ?? get(gpxStatistics); const statistics = get(gpxStatistics);
const slicedStatistics = get(slicedGPXStatistics);
const hovered = get(hoveredPoint);
const hidden = get(allHidden); const hidden = get(allHidden);
if (statistics.local.points.length > 0 && tool !== Tool.ROUTING && !hidden) { if (statistics.global.length > 0 && tool !== Tool.ROUTING && !hidden) {
this.start.setLngLat(statistics.local.points[0].getCoordinates()).addTo(map_); const start = statistics
this.end .getTrackPoint(slicedStatistics?.[1] ?? 0)!
.setLngLat( .trkpt.getCoordinates();
statistics.local.points[statistics.local.points.length - 1].getCoordinates() const end = statistics
) .getTrackPoint(slicedStatistics?.[2] ?? statistics.global.length - 1)!
.addTo(map_); .trkpt.getCoordinates();
const data: GeoJSON.FeatureCollection = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [start.lon, start.lat],
},
properties: {
icon: 'start-marker',
},
},
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [end.lon, end.lat],
},
properties: {
icon: 'end-marker',
},
},
],
};
if (hovered) {
data.features.push({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [hovered.lon, hovered.lat],
},
properties: {
icon: 'hover-marker',
},
});
}
let source = map_.getSource('start-end-markers') as GeoJSONSource | undefined;
if (source) {
source.setData(data);
} else {
map_.addSource('start-end-markers', {
type: 'geojson',
data: data,
});
}
if (!map_.getLayer('start-end-markers')) {
map_.addLayer(
{
id: 'start-end-markers',
type: 'symbol',
source: 'start-end-markers',
layout: {
'icon-image': ['get', 'icon'],
'icon-size': 0.2,
'icon-allow-overlap': true,
},
},
ANCHOR_LAYER_KEY.startEndMarkers
);
}
} else { } else {
this.start.remove(); if (map_.getLayer('start-end-markers')) {
this.end.remove(); map_.removeLayer('start-end-markers');
}
if (map_.getSource('start-end-markers')) {
map_.removeSource('start-end-markers');
}
} }
} }
remove() { remove() {
this.unsubscribes.forEach((unsubscribe) => unsubscribe()); this.unsubscribes.forEach((unsubscribe) => unsubscribe());
this.start.remove(); const map_ = get(map);
this.end.remove(); if (!map_) return;
if (map_.getLayer('start-end-markers')) {
map_.removeLayer('start-end-markers');
}
if (map_.getSource('start-end-markers')) {
map_.removeSource('start-end-markers');
}
}
loadIcons() {
const map_ = get(map);
if (!map_) return;
loadSVGIcon(map_, 'start-marker', startMarkerSVG);
loadSVGIcon(map_, 'end-marker', endMarkerSVG);
loadSVGIcon(map_, 'hover-marker', hoverMarkerSVG);
} }
} }

View File

@@ -20,9 +20,8 @@
import { i18n } from '$lib/i18n.svelte'; import { i18n } from '$lib/i18n.svelte';
import { defaultBasemap, type CustomLayer } from '$lib/assets/layers'; import { defaultBasemap, type CustomLayer } from '$lib/assets/layers';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { customBasemapUpdate, isSelected, remove } from './utils'; import { remove } from './utils';
import { settings } from '$lib/logic/settings'; import { settings } from '$lib/logic/settings';
import { map } from '$lib/components/map/map';
import { dndzone } from 'svelte-dnd-action'; import { dndzone } from 'svelte-dnd-action';
const { const {
@@ -42,13 +41,8 @@
let maxZoom: number = $state(20); let maxZoom: number = $state(20);
let layerType: 'basemap' | 'overlay' = $state('basemap'); let layerType: 'basemap' | 'overlay' = $state('basemap');
let resourceType: 'raster' | 'vector' = $derived.by(() => { let resourceType: 'raster' | 'vector' = $derived.by(() => {
if (tileUrls[0].length > 0) { if (tileUrls[0].length > 0 && tileUrls[0].includes('.json')) {
if ( return 'vector';
tileUrls[0].includes('.json') ||
(tileUrls[0].includes('api.mapbox.com/styles') && !tileUrls[0].includes('tiles'))
) {
return 'vector';
}
} }
return 'raster'; return 'raster';
}); });
@@ -134,8 +128,8 @@
], ],
}; };
} }
$customLayers[layerId] = layer;
addLayer(layerId); addLayer(layerId);
$customLayers[layerId] = layer;
selectedLayerId = undefined; selectedLayerId = undefined;
setDataFromSelectedLayer(); setDataFromSelectedLayer();
} }
@@ -158,9 +152,7 @@
return $tree; return $tree;
}); });
if ($currentBasemap === layerId) { if ($currentBasemap !== layerId) {
$customBasemapUpdate++;
} else {
$currentBasemap = layerId; $currentBasemap = layerId;
} }
@@ -176,14 +168,6 @@
return $tree; return $tree;
}); });
if ($map && $currentOverlays && isSelected($currentOverlays, layerId)) {
try {
$map.removeImport(layerId);
} catch (e) {
// No reliable way to check if the map is ready to remove sources and layers
}
}
currentOverlays.update(($overlays) => { currentOverlays.update(($overlays) => {
if (!$overlays.overlays.hasOwnProperty('custom')) { if (!$overlays.overlays.hasOwnProperty('custom')) {
$overlays.overlays['custom'] = {}; $overlays.overlays['custom'] = {};

View File

@@ -5,12 +5,8 @@
import { Separator } from '$lib/components/ui/separator'; import { Separator } from '$lib/components/ui/separator';
import { ScrollArea } from '$lib/components/ui/scroll-area/index.js'; import { ScrollArea } from '$lib/components/ui/scroll-area/index.js';
import { Layers } from '@lucide/svelte'; import { Layers } from '@lucide/svelte';
import { basemaps, defaultBasemap, overlays } from '$lib/assets/layers';
import { settings } from '$lib/logic/settings'; import { settings } from '$lib/logic/settings';
import { map } from '$lib/components/map/map'; import { map } from '$lib/components/map/map';
import { customBasemapUpdate, getLayers } from './utils';
import type { ImportSpecification, StyleSpecification } from 'mapbox-gl';
import { untrack } from 'svelte';
let container: HTMLDivElement; let container: HTMLDivElement;
let overpassLayer: OverpassLayer; let overpassLayer: OverpassLayer;
@@ -23,127 +19,14 @@
selectedBasemapTree, selectedBasemapTree,
selectedOverlayTree, selectedOverlayTree,
selectedOverpassTree, selectedOverpassTree,
customLayers,
opacities,
} = settings; } = settings;
function setStyle() { map.onLoad((_map: maplibregl.Map) => {
if (!$map) {
return;
}
let basemap = basemaps.hasOwnProperty($currentBasemap)
? basemaps[$currentBasemap]
: ($customLayers[$currentBasemap]?.value ?? basemaps[defaultBasemap]);
$map.removeImport('basemap');
if (typeof basemap === 'string') {
$map.addImport({ id: 'basemap', url: basemap }, 'overlays');
} else {
$map.addImport(
{
id: 'basemap',
url: '',
data: basemap as StyleSpecification,
},
'overlays'
);
}
}
$effect(() => {
if ($map && ($currentBasemap || $customBasemapUpdate)) {
untrack(() => setStyle());
}
});
function addOverlay(id: string) {
if (!$map) {
return;
}
try {
let overlay = $customLayers.hasOwnProperty(id) ? $customLayers[id].value : overlays[id];
if (typeof overlay === 'string') {
$map.addImport({ id, url: overlay });
} else {
if ($opacities.hasOwnProperty(id)) {
overlay = {
...overlay,
layers: (overlay as StyleSpecification).layers.map((layer) => {
if (layer.type === 'raster') {
if (!layer.paint) {
layer.paint = {};
}
layer.paint['raster-opacity'] = $opacities[id];
}
return layer;
}),
};
}
$map.addImport({
id,
url: '',
data: overlay as StyleSpecification,
});
}
} catch (e) {
// No reliable way to check if the map is ready to add sources and layers
}
}
function updateOverlays() {
if ($map && $currentOverlays && $opacities) {
let overlayLayers = getLayers($currentOverlays);
try {
let activeOverlays =
$map
.getStyle()
.imports?.reduce(
(
acc: Record<string, ImportSpecification>,
imprt: ImportSpecification
) => {
if (
!['basemap', 'overlays', 'glyphs-and-sprite'].includes(imprt.id)
) {
acc[imprt.id] = imprt;
}
return acc;
},
{}
) || {};
let toRemove = Object.keys(activeOverlays).filter((id) => !overlayLayers[id]);
toRemove.forEach((id) => {
$map?.removeImport(id);
});
let toAdd = Object.entries(overlayLayers)
.filter(([id, selected]) => selected && !activeOverlays.hasOwnProperty(id))
.map(([id]) => id);
toAdd.forEach((id) => {
addOverlay(id);
});
} catch (e) {
// No reliable way to check if the map is ready to add sources and layers
}
}
}
$effect(() => {
if ($map && $currentOverlays && $opacities) {
untrack(() => updateOverlays());
}
});
map.onLoad((_map: mapboxgl.Map) => {
if (overpassLayer) { if (overpassLayer) {
overpassLayer.remove(); overpassLayer.remove();
} }
overpassLayer = new OverpassLayer(_map); overpassLayer = new OverpassLayer(_map, map.layerEventManager!);
overpassLayer.add(); overpassLayer.add();
let first = true;
_map.on('style.import.load', () => {
if (!first) return;
first = false;
updateOverlays();
});
}); });
let open = $state(false); let open = $state(false);

View File

@@ -13,6 +13,7 @@
overlays, overlays,
overlayTree, overlayTree,
overpassTree, overpassTree,
terrainSources,
} from '$lib/assets/layers'; } from '$lib/assets/layers';
import { getLayers, isSelected, toggle } from '$lib/components/map/layer-control/utils'; import { getLayers, isSelected, toggle } from '$lib/components/map/layer-control/utils';
import { i18n } from '$lib/i18n.svelte'; import { i18n } from '$lib/i18n.svelte';
@@ -31,6 +32,7 @@
currentOverpassQueries, currentOverpassQueries,
customLayers, customLayers,
opacities, opacities,
terrainSource,
} = settings; } = settings;
const { isLayerFromExtension, getLayerName } = extensionAPI; const { isLayerFromExtension, getLayerName } = extensionAPI;
@@ -54,7 +56,7 @@
} }
$effect(() => { $effect(() => {
if ($selectedBasemapTree && $currentBasemap) { if (open && $selectedBasemapTree && $currentBasemap) {
if (!isSelected($selectedBasemapTree, $currentBasemap)) { if (!isSelected($selectedBasemapTree, $currentBasemap)) {
if (!isSelected($selectedBasemapTree, defaultBasemap)) { if (!isSelected($selectedBasemapTree, defaultBasemap)) {
$selectedBasemapTree = toggle($selectedBasemapTree, defaultBasemap); $selectedBasemapTree = toggle($selectedBasemapTree, defaultBasemap);
@@ -65,7 +67,7 @@
}); });
$effect(() => { $effect(() => {
if ($selectedOverlayTree) { if (open && $selectedOverlayTree) {
untrack(() => { untrack(() => {
if ($currentOverlays) { if ($currentOverlays) {
let overlayLayers = getLayers($currentOverlays); let overlayLayers = getLayers($currentOverlays);
@@ -86,7 +88,7 @@
}); });
$effect(() => { $effect(() => {
if ($selectedOverpassTree) { if (open && $selectedOverpassTree) {
untrack(() => { untrack(() => {
if ($currentOverpassQueries) { if ($currentOverpassQueries) {
let overlayLayers = getLayers($currentOverpassQueries); let overlayLayers = getLayers($currentOverpassQueries);
@@ -165,11 +167,11 @@
{#if isSelected($selectedOverlayTree, selectedOverlay)} {#if isSelected($selectedOverlayTree, selectedOverlay)}
{#if $isLayerFromExtension(selectedOverlay)} {#if $isLayerFromExtension(selectedOverlay)}
{$getLayerName(selectedOverlay)} {$getLayerName(selectedOverlay)}
{:else if $customLayers.hasOwnProperty(selectedOverlay)}
{$customLayers[selectedOverlay].name}
{:else} {:else}
{i18n._(`layers.label.${selectedOverlay}`)} {i18n._(`layers.label.${selectedOverlay}`)}
{/if} {/if}
{:else if $customLayers.hasOwnProperty(selectedOverlay)}
{$customLayers[selectedOverlay].name}
{/if} {/if}
{/if} {/if}
</Select.Trigger> </Select.Trigger>
@@ -211,7 +213,9 @@
isSelected($currentOverlays, selectedOverlay) isSelected($currentOverlays, selectedOverlay)
) { ) {
try { try {
$map.removeImport(selectedOverlay); if ($map.getLayer(selectedOverlay)) {
$map.removeLayer(selectedOverlay);
}
} catch (e) { } catch (e) {
// No reliable way to check if the map is ready to remove sources and layers // No reliable way to check if the map is ready to remove sources and layers
} }
@@ -233,6 +237,23 @@
</ScrollArea> </ScrollArea>
</Accordion.Content> </Accordion.Content>
</Accordion.Item> </Accordion.Item>
<Accordion.Item value="terrain-source">
<Accordion.Trigger>{i18n._('layers.terrain')}</Accordion.Trigger>
<Accordion.Content class="flex flex-col gap-3 overflow-visible">
<Select.Root bind:value={$terrainSource} type="single">
<Select.Trigger class="mr-1 w-full" size="sm">
{i18n._(`layers.label.${$terrainSource}`)}
</Select.Trigger>
<Select.Content class="h-fit max-h-[40dvh] overflow-y-auto">
{#each Object.keys(terrainSources) as id}
<Select.Item value={id}>
{i18n._(`layers.label.${id}`)}
</Select.Item>
{/each}
</Select.Content>
</Select.Root>
</Accordion.Content>
</Accordion.Item>
</Accordion.Root> </Accordion.Root>
</ScrollArea> </ScrollArea>
</Sheet.Header> </Sheet.Header>

View File

@@ -54,28 +54,27 @@
<Card.Root class="border-none shadow-md text-base p-2 max-w-[50dvw] gap-0"> <Card.Root class="border-none shadow-md text-base p-2 max-w-[50dvw] gap-0">
<Card.Header class="p-0 gap-0"> <Card.Header class="p-0 gap-0">
<Card.Title class="text-md"> <Card.Title class="text-md flex flex-row">
<div class="flex flex-row gap-3"> <div class="flex flex-col">
<div class="flex flex-col"> <p>{name}</p>
{name} <div class="text-muted-foreground text-xs font-normal">
<div class="text-muted-foreground text-xs font-normal"> {poi.item.lat.toFixed(6)}&deg; {poi.item.lon.toFixed(6)}&deg;
{poi.item.lat.toFixed(6)}&deg; {poi.item.lon.toFixed(6)}&deg;
</div>
</div> </div>
<Button
class="ml-auto"
variant="outline"
size="icon"
href="https://www.openstreetmap.org/edit?editor=id&{poi.item.type ??
'node'}={poi.item.id}"
target="_blank"
>
<PencilLine size="16" />
</Button>
</div> </div>
<Button
class="ml-auto"
variant="outline"
size="icon-sm"
href="https://www.openstreetmap.org/edit?editor=id&{poi.item.type ?? 'node'}={poi
.item.id}"
target="_blank"
>
<PencilLine size="16" />
</Button>
</Card.Title> </Card.Title>
</Card.Header> </Card.Header>
<Card.Content class="flex flex-col p-0 text-sm mt-1 whitespace-normal break-all"> <Card.Content class="flex flex-col gap-1 p-0 text-sm whitespace-normal break-all">
<ScrollArea class="flex flex-col max-h-[30dvh]"> <ScrollArea class="flex flex-col max-h-[30dvh]">
{#if tags.image || tags['image:0']} {#if tags.image || tags['image:0']}
<div class="w-full rounded-md overflow-clip my-2 max-w-96 mx-auto"> <div class="w-full rounded-md overflow-clip my-2 max-w-96 mx-auto">
@@ -100,8 +99,14 @@
{/each} {/each}
</div> </div>
</ScrollArea> </ScrollArea>
<Button class="mt-2" variant="outline" disabled={$selection.size === 0} onclick={addToFile}> <Button
<MapPin size="16" /> size="sm"
class="mt-1 justify-start"
variant="outline"
disabled={$selection.size === 0}
onclick={addToFile}
>
<MapPin size="14" />
{i18n._('toolbar.waypoint.add')} {i18n._('toolbar.waypoint.add')}
</Button> </Button>
</Card.Content> </Card.Content>

View File

@@ -103,7 +103,7 @@ export class ExtensionAPI {
if (current && isSelected(current, overlay.id)) { if (current && isSelected(current, overlay.id)) {
show = true; show = true;
try { try {
get(map)?.removeImport(overlay.id); get(map)?.removeLayer(overlay.id);
} catch (e) { } catch (e) {
// No reliable way to check if the map is ready to remove sources and layers // No reliable way to check if the map is ready to remove sources and layers
} }

View File

@@ -6,6 +6,10 @@ import { overpassQueryData } from '$lib/assets/layers';
import { MapPopup } from '$lib/components/map/map-popup'; import { MapPopup } from '$lib/components/map/map-popup';
import { settings } from '$lib/logic/settings'; import { settings } from '$lib/logic/settings';
import { db } from '$lib/db'; import { db } from '$lib/db';
import type { GeoJSONSource } from 'maplibre-gl';
import { ANCHOR_LAYER_KEY } from '../style';
import type { MapLayerEventManager } from '$lib/components/map/map-layer-event-manager';
import { loadSVGIcon } from '$lib/utils';
const { currentOverpassQueries } = settings; const { currentOverpassQueries } = settings;
@@ -20,11 +24,12 @@ liveQuery(() => db.overpassdata.toArray()).subscribe((pois) => {
}); });
export class OverpassLayer { export class OverpassLayer {
overpassUrl = 'https://overpass.private.coffee/api/interpreter'; overpassUrl = 'https://maps.mail.ru/osm/tools/overpass/api/interpreter';
minZoom = 12; minZoom = 12;
queryZoom = 12; queryZoom = 12;
expirationTime = 7 * 24 * 3600 * 1000; expirationTime = 7 * 24 * 3600 * 1000;
map: mapboxgl.Map; map: maplibregl.Map;
layerEventManager: MapLayerEventManager;
popup: MapPopup; popup: MapPopup;
currentQueries: Set<string> = new Set(); currentQueries: Set<string> = new Set();
@@ -35,8 +40,9 @@ export class OverpassLayer {
updateBinded = this.update.bind(this); updateBinded = this.update.bind(this);
onHoverBinded = this.onHover.bind(this); onHoverBinded = this.onHover.bind(this);
constructor(map: mapboxgl.Map) { constructor(map: maplibregl.Map, layerEventManager: MapLayerEventManager) {
this.map = map; this.map = map;
this.layerEventManager = layerEventManager;
this.popup = new MapPopup(map, { this.popup = new MapPopup(map, {
closeButton: false, closeButton: false,
focusAfterOpen: false, focusAfterOpen: false,
@@ -47,7 +53,7 @@ export class OverpassLayer {
add() { add() {
this.map.on('moveend', this.queryIfNeededBinded); this.map.on('moveend', this.queryIfNeededBinded);
this.map.on('style.import.load', this.updateBinded); this.map.on('style.load', this.updateBinded);
this.unsubscribes.push(data.subscribe(this.updateBinded)); this.unsubscribes.push(data.subscribe(this.updateBinded));
this.unsubscribes.push( this.unsubscribes.push(
currentOverpassQueries.subscribe(() => { currentOverpassQueries.subscribe(() => {
@@ -71,10 +77,17 @@ export class OverpassLayer {
update() { update() {
this.loadIcons(); this.loadIcons();
let d = get(data); const fullData = get(data);
const queries = getCurrentQueries();
const d: GeoJSON.FeatureCollection = {
type: 'FeatureCollection',
features: fullData.features.filter((feature) =>
queries.includes(feature.properties!.query)
),
};
try { try {
let source = this.map.getSource('overpass') as mapboxgl.GeoJSONSource | undefined; let source = this.map.getSource('overpass') as GeoJSONSource | undefined;
if (source) { if (source) {
source.setData(d); source.setData(d);
} else { } else {
@@ -85,25 +98,24 @@ export class OverpassLayer {
} }
if (!this.map.getLayer('overpass')) { if (!this.map.getLayer('overpass')) {
this.map.addLayer({ this.map.addLayer(
id: 'overpass', {
type: 'symbol', id: 'overpass',
source: 'overpass', type: 'symbol',
layout: { source: 'overpass',
'icon-image': ['get', 'icon'], layout: {
'icon-size': 0.25, 'icon-image': ['get', 'icon'],
'icon-padding': 0, 'icon-size': 0.25,
'icon-allow-overlap': ['step', ['zoom'], false, 14, true], 'icon-padding': 0,
'icon-allow-overlap': ['step', ['zoom'], false, 14, true],
},
}, },
}); ANCHOR_LAYER_KEY.overpass
);
this.map.on('mouseenter', 'overpass', this.onHoverBinded); this.layerEventManager.on('mouseenter', 'overpass', this.onHoverBinded);
this.map.on('click', 'overpass', this.onHoverBinded); this.layerEventManager.on('click', 'overpass', this.onHoverBinded);
} }
this.map.setFilter('overpass', ['in', 'query', ...getCurrentQueries()], {
validate: false,
});
} catch (e) { } catch (e) {
// No reliable way to check if the map is ready to add sources and layers // No reliable way to check if the map is ready to add sources and layers
} }
@@ -111,7 +123,9 @@ export class OverpassLayer {
remove() { remove() {
this.map.off('moveend', this.queryIfNeededBinded); this.map.off('moveend', this.queryIfNeededBinded);
this.map.off('style.import.load', this.updateBinded); this.map.off('style.load', this.updateBinded);
this.layerEventManager.off('mouseenter', 'overpass', this.onHoverBinded);
this.layerEventManager.off('click', 'overpass', this.onHoverBinded);
this.unsubscribes.forEach((unsubscribe) => unsubscribe()); this.unsubscribes.forEach((unsubscribe) => unsubscribe());
try { try {
@@ -244,27 +258,16 @@ export class OverpassLayer {
loadIcons() { loadIcons() {
let currentQueries = getCurrentQueries(); let currentQueries = getCurrentQueries();
currentQueries.forEach((query) => { currentQueries.forEach((query) => {
if (!this.map.hasImage(`overpass-${query}`)) { loadSVGIcon(
let icon = new Image(100, 100); this.map,
icon.onload = () => { `overpass-${query}`,
if (!this.map.hasImage(`overpass-${query}`)) { `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">
this.map.addImage(`overpass-${query}`, icon);
}
};
// Lucide icons are SVG files with a 24x24 viewBox
// Create a new SVG with a 32x32 viewBox and center the icon in a circle
icon.src =
'data:image/svg+xml,' +
encodeURIComponent(`
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">
<circle cx="20" cy="20" r="20" fill="${overpassQueryData[query].icon.color}" /> <circle cx="20" cy="20" r="20" fill="${overpassQueryData[query].icon.color}" />
<g transform="translate(8 8)"> <g transform="translate(8 8)">
${overpassQueryData[query].icon.svg.replace('stroke="currentColor"', 'stroke="white"')} ${overpassQueryData[query].icon.svg.replace('stroke="currentColor"', 'stroke="white"')}
</g> </g>
</svg> </svg>`
`); );
}
}); });
} }
} }

View File

@@ -76,5 +76,3 @@ export function removeAll(node: LayerTreeType, ids: string[]) {
}); });
return node; return node;
} }
export const customBasemapUpdate = writable(0);

View File

@@ -0,0 +1,287 @@
import { fileStateCollection } from '$lib/logic/file-state';
import maplibregl from 'maplibre-gl';
type MapLayerMouseEventListener = (e: maplibregl.MapLayerMouseEvent) => void;
type MapLayerTouchEventListener = (e: maplibregl.MapLayerTouchEvent) => void;
type MapLayerListener = {
features: maplibregl.MapGeoJSONFeature[];
mousemoves: MapLayerMouseEventListener[];
mouseenters: MapLayerMouseEventListener[];
mouseleaves: MapLayerMouseEventListener[];
mousedowns: MapLayerMouseEventListener[];
clicks: MapLayerMouseEventListener[];
contextmenus: MapLayerMouseEventListener[];
touchstarts: MapLayerTouchEventListener[];
};
export class MapLayerEventManager {
private _map: maplibregl.Map;
private _listeners: Record<string, MapLayerListener> = {};
constructor(map: maplibregl.Map) {
this._map = map;
this._map.on('mousemove', this._handleMouseMove.bind(this));
this._map.on('click', this._handleMouseClick.bind(this, 'click'));
this._map.on('contextmenu', this._handleMouseClick.bind(this, 'contextmenu'));
this._map.on('mousedown', this._handleMouseClick.bind(this, 'mousedown'));
this._map.on('touchstart', this._handleTouchStart.bind(this));
}
on(
eventType:
| 'mousemove'
| 'mouseenter'
| 'mouseleave'
| 'mousedown'
| 'click'
| 'contextmenu'
| 'touchstart',
layerId: string,
listener: MapLayerMouseEventListener | MapLayerTouchEventListener
) {
if (!this._listeners[layerId]) {
this._listeners[layerId] = {
features: [],
mousemoves: [],
mouseenters: [],
mouseleaves: [],
mousedowns: [],
clicks: [],
contextmenus: [],
touchstarts: [],
};
}
switch (eventType) {
case 'mousemove':
this._listeners[layerId].mousemoves.push(listener as MapLayerMouseEventListener);
break;
case 'mouseenter':
this._listeners[layerId].mouseenters.push(listener as MapLayerMouseEventListener);
break;
case 'mouseleave':
this._listeners[layerId].mouseleaves.push(listener as MapLayerMouseEventListener);
break;
case 'mousedown':
this._listeners[layerId].mousedowns.push(listener as MapLayerMouseEventListener);
break;
case 'click':
this._listeners[layerId].clicks.push(listener as MapLayerMouseEventListener);
break;
case 'contextmenu':
this._listeners[layerId].contextmenus.push(listener as MapLayerMouseEventListener);
break;
case 'touchstart':
this._listeners[layerId].touchstarts.push(listener as MapLayerTouchEventListener);
break;
}
}
off(
eventType:
| 'mousemove'
| 'mouseenter'
| 'mouseleave'
| 'mousedown'
| 'click'
| 'contextmenu'
| 'touchstart',
layerId: string,
listener: MapLayerMouseEventListener | MapLayerTouchEventListener
) {
if (this._listeners[layerId]) {
switch (eventType) {
case 'mousemove':
this._listeners[layerId].mousemoves = this._listeners[
layerId
].mousemoves.filter((l) => l !== listener);
break;
case 'mouseenter':
this._listeners[layerId].mouseenters = this._listeners[
layerId
].mouseenters.filter((l) => l !== listener);
break;
case 'mouseleave':
this._listeners[layerId].mouseleaves = this._listeners[
layerId
].mouseleaves.filter((l) => l !== listener);
break;
case 'mousedown':
this._listeners[layerId].mousedowns = this._listeners[
layerId
].mousedowns.filter((l) => l !== listener);
break;
case 'click':
this._listeners[layerId].clicks = this._listeners[layerId].clicks.filter(
(l) => l !== listener
);
break;
case 'contextmenu':
this._listeners[layerId].contextmenus = this._listeners[
layerId
].contextmenus.filter((l) => l !== listener);
break;
case 'touchstart':
this._listeners[layerId].touchstarts = this._listeners[
layerId
].touchstarts.filter((l) => l !== listener);
break;
}
if (
this._listeners[layerId].mousemoves.length === 0 &&
this._listeners[layerId].mouseenters.length === 0 &&
this._listeners[layerId].mouseleaves.length === 0 &&
this._listeners[layerId].mousedowns.length === 0 &&
this._listeners[layerId].clicks.length === 0 &&
this._listeners[layerId].contextmenus.length === 0 &&
this._listeners[layerId].touchstarts.length === 0
) {
delete this._listeners[layerId];
}
}
}
private _handleMouseMove(e: maplibregl.MapMouseEvent) {
const layerIds = this._filterLayersIntersectingBounds(
Object.keys(this._listeners),
this._getBounds(e.point)
);
const features =
layerIds.length > 0
? this._map.queryRenderedFeatures(e.point, { layers: layerIds })
: [];
const featuresByLayer: Record<string, maplibregl.MapGeoJSONFeature[]> = {};
features.forEach((f) => {
if (!featuresByLayer[f.layer.id]) {
featuresByLayer[f.layer.id] = [];
}
featuresByLayer[f.layer.id].push(f);
});
Object.keys(this._listeners).forEach((layerId) => {
const features = featuresByLayer[layerId] || [];
const listener = this._listeners[layerId];
if ((features.length == 0) != (listener.features.length == 0)) {
if (features.length > 0) {
if (listener.mouseenters.length > 0) {
const event = new maplibregl.MapMouseEvent(
'mouseenter',
e.target,
e.originalEvent,
{
features: featuresByLayer[layerId]!,
}
);
listener.mouseenters.forEach((l) => l(event));
}
} else {
if (listener.mouseleaves.length > 0) {
const event = new maplibregl.MapMouseEvent(
'mouseleave',
e.target,
e.originalEvent
);
listener.mouseleaves.forEach((l) => l(event));
}
}
listener.features = features;
}
if (features.length > 0 && listener.mousemoves.length > 0) {
const event = new maplibregl.MapMouseEvent('mousemove', e.target, e.originalEvent, {
features: featuresByLayer[layerId]!,
});
listener.mousemoves.forEach((l) => l(event));
}
});
}
private _handleMouseClick(type: string, e: maplibregl.MapMouseEvent) {
Object.values(this._listeners).forEach((listener) => {
if (listener.features.length > 0) {
if (type === 'click' && listener.clicks.length > 0) {
const event = new maplibregl.MapMouseEvent('click', e.target, e.originalEvent, {
features: listener.features,
});
listener.clicks.forEach((l) => l(event));
} else if (type === 'contextmenu' && listener.contextmenus.length > 0) {
const event = new maplibregl.MapMouseEvent(
'contextmenu',
e.target,
e.originalEvent,
{
features: listener.features,
}
);
listener.contextmenus.forEach((l) => l(event));
} else if (type === 'mousedown' && listener.mousedowns.length > 0) {
const event = new maplibregl.MapMouseEvent(
'mousedown',
e.target,
e.originalEvent,
{
features: listener.features,
}
);
listener.mousedowns.forEach((l) => l(event));
}
}
});
}
private _handleTouchStart(e: maplibregl.MapTouchEvent) {
const layerIds = this._filterLayersIntersectingBounds(
Object.keys(this._listeners).filter(
(layerId) => this._listeners[layerId].touchstarts.length > 0
),
this._getBounds(e.point)
);
if (layerIds.length === 0) return;
const features = this._map.queryRenderedFeatures(e.points[0], { layers: layerIds });
const featuresByLayer: Record<string, maplibregl.MapGeoJSONFeature[]> = {};
features.forEach((f) => {
if (!featuresByLayer[f.layer.id]) {
featuresByLayer[f.layer.id] = [];
}
featuresByLayer[f.layer.id].push(f);
});
Object.keys(this._listeners).forEach((layerId) => {
const features = featuresByLayer[layerId] || [];
const listener = this._listeners[layerId];
if (features.length > 0) {
const event: maplibregl.MapLayerTouchEvent = new maplibregl.MapTouchEvent(
'touchstart',
e.target,
e.originalEvent
);
event.features = featuresByLayer[layerId]!;
listener.touchstarts.forEach((l) => l(event));
}
});
}
private _getBounds(point: maplibregl.Point) {
const delta = 30;
return new maplibregl.LngLatBounds(
this._map.unproject([point.x - delta, point.y + delta]),
this._map.unproject([point.x + delta, point.y - delta])
);
}
private _filterLayersIntersectingBounds(
layerIds: string[],
bounds: maplibregl.LngLatBounds
): string[] {
let result = layerIds.filter((layerId) => {
if (!this._map.getLayer(layerId)) return false;
const fileId = layerId.replace('-waypoints', '');
if (fileId === layerId) {
return fileStateCollection.getStatistics(fileId)?.intersectsBBox(bounds) ?? true;
} else {
return (
fileStateCollection.getStatistics(fileId)?.intersectsWaypointBBox(bounds) ??
true
);
}
});
return result;
}
}

View File

@@ -1,5 +1,5 @@
import { TrackPoint, Waypoint } from 'gpx'; import { TrackPoint, Waypoint } from 'gpx';
import mapboxgl from 'mapbox-gl'; import maplibregl from 'maplibre-gl';
import { mount, tick, unmount } from 'svelte'; import { mount, tick, unmount } from 'svelte';
import { get, writable, type Writable } from 'svelte/store'; import { get, writable, type Writable } from 'svelte/store';
import MapPopupComponent from '$lib/components/map/MapPopup.svelte'; import MapPopupComponent from '$lib/components/map/MapPopup.svelte';
@@ -11,15 +11,15 @@ export type PopupItem<T = Waypoint | TrackPoint | any> = {
}; };
export class MapPopup { export class MapPopup {
map: mapboxgl.Map; map: maplibregl.Map;
popup: mapboxgl.Popup; popup: maplibregl.Popup;
item: Writable<PopupItem | null> = writable(null); item: Writable<PopupItem | null> = writable(null);
component: ReturnType<typeof mount>; component: ReturnType<typeof mount>;
maybeHideBinded = this.maybeHide.bind(this); maybeHideBinded = this.maybeHide.bind(this);
constructor(map: mapboxgl.Map, options?: mapboxgl.PopupOptions) { constructor(map: maplibregl.Map, options?: maplibregl.PopupOptions) {
this.map = map; this.map = map;
this.popup = new mapboxgl.Popup(options); this.popup = new maplibregl.Popup(options);
this.component = mount(MapPopupComponent, { this.component = mount(MapPopupComponent, {
target: document.body, target: document.body,
props: { props: {
@@ -51,7 +51,7 @@ export class MapPopup {
this.map.on('mousemove', this.maybeHideBinded); this.map.on('mousemove', this.maybeHideBinded);
} }
maybeHide(e: mapboxgl.MapMouseEvent) { maybeHide(e: maplibregl.MapMouseEvent) {
const item = get(this.item); const item = get(this.item);
if (item === null) { if (item === null) {
this.hide(); this.hide();
@@ -75,10 +75,10 @@ export class MapPopup {
getCoordinates() { getCoordinates() {
const item = get(this.item); const item = get(this.item);
if (item === null) { if (item === null) {
return new mapboxgl.LngLat(0, 0); return new maplibregl.LngLat(0, 0);
} }
return item.item instanceof Waypoint || item.item instanceof TrackPoint return item.item instanceof Waypoint || item.item instanceof TrackPoint
? item.item.getCoordinates() ? item.item.getCoordinates()
: new mapboxgl.LngLat(item.item.lon, item.item.lat); : new maplibregl.LngLat(item.item.lon, item.item.lat);
} }
} }

View File

@@ -1,100 +1,80 @@
import mapboxgl from 'mapbox-gl'; import maplibregl from 'maplibre-gl';
import MapboxGeocoder from '@mapbox/mapbox-gl-geocoder'; import 'maplibre-gl/dist/maplibre-gl.css';
import MaplibreGeocoder, {
type MaplibreGeocoderFeatureResults,
} from '@maplibre/maplibre-gl-geocoder';
import '@maplibre/maplibre-gl-geocoder/dist/maplibre-gl-geocoder.css';
import { get, writable, type Writable } from 'svelte/store'; import { get, writable, type Writable } from 'svelte/store';
import { settings } from '$lib/logic/settings'; import { settings } from '$lib/logic/settings';
import { tick } from 'svelte'; import { tick } from 'svelte';
import { ANCHOR_LAYER_KEY, StyleManager } from '$lib/components/map/style';
import { MapLayerEventManager } from '$lib/components/map/map-layer-event-manager';
const { treeFileView, elevationProfile, bottomPanelSize, rightPanelSize, distanceUnits } = settings; const { treeFileView, elevationProfile, bottomPanelSize, rightPanelSize, distanceUnits } = settings;
let fitBoundsOptions: mapboxgl.MapOptions['fitBoundsOptions'] = { let fitBoundsOptions: maplibregl.MapOptions['fitBoundsOptions'] = {
maxZoom: 15, maxZoom: 15,
linear: true, linear: true,
easing: () => 1, easing: () => 1,
}; };
export class MapboxGLMap { export class MapLibreGLMap {
private _map: Writable<mapboxgl.Map | null> = writable(null); private _maptilerKey: string = '';
private _onLoadCallbacks: ((map: mapboxgl.Map) => void)[] = []; private _map: maplibregl.Map | null = null;
private _mapStore: Writable<maplibregl.Map | null> = writable(null);
private _styleManager: StyleManager | null = null;
private _onLoadCallbacks: ((map: maplibregl.Map) => void)[] = [];
private _unsubscribes: (() => void)[] = []; private _unsubscribes: (() => void)[] = [];
private callOnLoadBinded: () => void = this.callOnLoad.bind(this);
public layerEventManager: MapLayerEventManager | null = null;
subscribe(run: (value: mapboxgl.Map | null) => void, invalidate?: () => void) { subscribe(run: (value: maplibregl.Map | null) => void, invalidate?: () => void) {
return this._map.subscribe(run, invalidate); return this._mapStore.subscribe(run, invalidate);
} }
init( init(
accessToken: string, maptilerKey: string,
language: string, language: string,
hash: boolean, hash: boolean,
geocoder: boolean, geocoder: boolean,
geolocate: boolean geolocate: boolean
) { ) {
const map = new mapboxgl.Map({ this._maptilerKey = maptilerKey;
this._styleManager = new StyleManager(this._mapStore, this._maptilerKey);
const map = new maplibregl.Map({
container: 'map', container: 'map',
style: { style: {
version: 8, version: 8,
projection: {
type: 'globe',
},
sources: {}, sources: {},
layers: [], layers: [],
imports: [
{
id: 'glyphs-and-sprite', // make Mapbox glyphs and sprite available to other styles
url: '',
data: {
version: 8,
sources: {},
layers: [],
glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
sprite: 'mapbox://sprites/mapbox/outdoors-v12',
},
},
{
id: 'basemap',
url: '',
},
{
id: 'overlays',
url: '',
data: {
version: 8,
sources: {},
layers: [],
},
},
],
}, },
projection: 'globe',
zoom: 0, zoom: 0,
hash: hash, hash: hash,
language,
attributionControl: false,
logoPosition: 'bottom-right',
boxZoom: false, boxZoom: false,
maxPitch: 85,
}); });
this.layerEventManager = new MapLayerEventManager(map);
map.addControl( map.addControl(
new mapboxgl.AttributionControl({ new maplibregl.NavigationControl({
compact: true,
})
);
map.addControl(
new mapboxgl.NavigationControl({
visualizePitch: true, visualizePitch: true,
}) })
); );
if (geocoder) { if (geocoder) {
let geocoder = new MapboxGeocoder({ let geocoder = new MaplibreGeocoder(
mapboxgl: mapboxgl, {
enableEventLogging: false, forwardGeocode: async (config) => {
collapsed: true, const results: MaplibreGeocoderFeatureResults = {
flyTo: fitBoundsOptions, features: [],
language, type: 'FeatureCollection',
localGeocoder: () => [], };
localGeocoderOnly: true, try {
externalGeocoder: (query: string) => const request = `https://nominatim.openstreetmap.org/search?format=json&q=${config.query}&limit=5&accept-language=${language}`;
fetch( const response = await fetch(request);
`https://nominatim.openstreetmap.org/search?format=json&q=${query}&limit=5&accept-language=${language}` const geojson = await response.json();
) results.features = geojson.map((result: any) => {
.then((response) => response.json())
.then((data) => {
return data.map((result: any) => {
return { return {
type: 'Feature', type: 'Feature',
geometry: { geometry: {
@@ -104,74 +84,43 @@ export class MapboxGLMap {
place_name: result.display_name, place_name: result.display_name,
}; };
}); });
}), } catch (e) {}
}); return results;
let onKeyDown = geocoder._onKeyDown; },
geocoder._onKeyDown = (e: KeyboardEvent) => { },
// Trigger search on Enter key only {
if (e.key === 'Enter') { maplibregl: maplibregl,
onKeyDown.apply(geocoder, [{ target: geocoder._inputEl }]); enableEventLogging: false,
} else if (geocoder._typeahead.data.length > 0) { collapsed: true,
geocoder._typeahead.clear(); flyTo: fitBoundsOptions,
language,
} }
}; );
map.addControl(geocoder); map.addControl(geocoder);
} }
if (geolocate) { if (geolocate) {
map.addControl( map.addControl(
new mapboxgl.GeolocateControl({ new maplibregl.GeolocateControl({
positionOptions: { positionOptions: {
enableHighAccuracy: true, enableHighAccuracy: true,
}, },
fitBoundsOptions, fitBoundsOptions,
trackUserLocation: true, trackUserLocation: true,
showUserHeading: true,
}) })
); );
} }
const scaleControl = new mapboxgl.ScaleControl({ const scaleControl = new maplibregl.ScaleControl({
unit: get(distanceUnits), unit: get(distanceUnits),
}); });
map.addControl(scaleControl); map.addControl(scaleControl);
map.on('style.load', () => {
map.addSource('mapbox-dem', {
type: 'raster-dem',
url: 'mapbox://mapbox.mapbox-terrain-dem-v1',
tileSize: 512,
maxzoom: 14,
});
if (map.getPitch() > 0) {
map.setTerrain({
source: 'mapbox-dem',
exaggeration: 1,
});
}
map.setFog({
color: 'rgb(186, 210, 235)',
'high-color': 'rgb(36, 92, 223)',
'horizon-blend': 0.1,
'space-color': 'rgb(156, 240, 255)',
});
map.on('pitch', () => {
if (map.getPitch() > 0) {
map.setTerrain({
source: 'mapbox-dem',
exaggeration: 1,
});
} else {
map.setTerrain(null);
}
});
});
map.on('load', () => { map.on('load', () => {
this._map.set(map); // only set the store after the map has loaded this._map = map;
this._mapStore.set(map); // only set the store after the map has loaded
window._map = map; // entry point for extensions window._map = map; // entry point for extensions
this.resize(); this.resize();
scaleControl.setUnit(get(distanceUnits)); scaleControl.setUnit(get(distanceUnits));
this._onLoadCallbacks.forEach((callback) => callback(map));
this._onLoadCallbacks = [];
}); });
map.on('style.load', this.callOnLoadBinded);
this._unsubscribes.push(treeFileView.subscribe(() => this.resize())); this._unsubscribes.push(treeFileView.subscribe(() => this.resize()));
this._unsubscribes.push(elevationProfile.subscribe(() => this.resize())); this._unsubscribes.push(elevationProfile.subscribe(() => this.resize()));
@@ -184,44 +133,48 @@ export class MapboxGLMap {
); );
} }
onLoad(callback: (map: mapboxgl.Map) => void) {
const map = get(this._map);
if (map) {
callback(map);
} else {
this._onLoadCallbacks.push(callback);
}
}
destroy() { destroy() {
const map = get(this._map); if (this._map) {
if (map) { this._map.remove();
map.remove(); this._mapStore.set(null);
this._map.set(null);
} }
this._unsubscribes.forEach((unsubscribe) => unsubscribe()); this._unsubscribes.forEach((unsubscribe) => unsubscribe());
this._unsubscribes = []; this._unsubscribes = [];
} }
resize() { resize() {
const map = get(this._map); if (this._map) {
if (map) {
tick().then(() => { tick().then(() => {
map.resize(); this._map?.resize();
}); });
} }
} }
toggle3D() { toggle3D() {
const map = get(this._map); if (this._map) {
if (map) { if (this._map.getPitch() === 0) {
if (map.getPitch() === 0) { this._map.easeTo({ pitch: 70 });
map.easeTo({ pitch: 70 });
} else { } else {
map.easeTo({ pitch: 0 }); this._map.easeTo({ pitch: 0 });
} }
} }
} }
onLoad(callback: (map: maplibregl.Map) => void) {
if (this._map) {
callback(this._map);
} else {
this._onLoadCallbacks.push(callback);
}
}
callOnLoad() {
if (this._map && this._map.getLayer(ANCHOR_LAYER_KEY.overlays)) {
this._onLoadCallbacks.forEach((callback) => callback(this._map!));
this._onLoadCallbacks = [];
this._map.off('style.load', this.callOnLoadBinded);
}
}
} }
export const map = new MapboxGLMap(); export const map = new MapLibreGLMap();

View File

@@ -20,9 +20,14 @@
let container: HTMLElement; let container: HTMLElement;
onMount(() => { onMount(() => {
map.onLoad((map: mapboxgl.Map) => { map.onLoad((map_: maplibregl.Map) => {
googleRedirect = new GoogleRedirect(map); googleRedirect = new GoogleRedirect(map_);
mapillaryLayer = new MapillaryLayer(map, container, mapillaryOpen); mapillaryLayer = new MapillaryLayer(
map_,
map.layerEventManager!,
container,
mapillaryOpen
);
}); });
}); });

View File

@@ -1,11 +1,10 @@
import { mapCursor, MapCursorState } from '$lib/logic/map-cursor'; import { mapCursor, MapCursorState } from '$lib/logic/map-cursor';
import type mapboxgl from 'mapbox-gl';
export class GoogleRedirect { export class GoogleRedirect {
map: mapboxgl.Map; map: maplibregl.Map;
enabled = false; enabled = false;
constructor(map: mapboxgl.Map) { constructor(map: maplibregl.Map) {
this.map = map; this.map = map;
} }
@@ -25,7 +24,7 @@ export class GoogleRedirect {
this.map.off('click', this.openStreetView); this.map.off('click', this.openStreetView);
} }
openStreetView(e: mapboxgl.MapMouseEvent) { openStreetView(e: maplibregl.MapMouseEvent) {
window.open( window.open(
`https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=${e.lngLat.lat},${e.lngLat.lng}` `https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=${e.lngLat.lat},${e.lngLat.lng}`
); );

View File

@@ -1,7 +1,9 @@
import mapboxgl, { type LayerSpecification, type VectorSourceSpecification } from 'mapbox-gl'; import maplibregl, { type LayerSpecification, type VectorSourceSpecification } from 'maplibre-gl';
import { Viewer, type ViewerBearingEvent } from 'mapillary-js/dist/mapillary.module'; import { Viewer, type ViewerBearingEvent } from 'mapillary-js/dist/mapillary.module';
import 'mapillary-js/dist/mapillary.css'; import 'mapillary-js/dist/mapillary.css';
import { mapCursor, MapCursorState } from '$lib/logic/map-cursor'; import { mapCursor, MapCursorState } from '$lib/logic/map-cursor';
import { ANCHOR_LAYER_KEY } from '../style';
import type { MapLayerEventManager } from '$lib/components/map/map-layer-event-manager';
const mapillarySource: VectorSourceSpecification = { const mapillarySource: VectorSourceSpecification = {
type: 'vector', type: 'vector',
@@ -41,8 +43,9 @@ const mapillaryImageLayer: LayerSpecification = {
}; };
export class MapillaryLayer { export class MapillaryLayer {
map: mapboxgl.Map; map: maplibregl.Map;
marker: mapboxgl.Marker; layerEventManager: MapLayerEventManager;
marker: maplibregl.Marker;
viewer: Viewer; viewer: Viewer;
active = false; active = false;
@@ -52,8 +55,14 @@ export class MapillaryLayer {
onMouseEnterBinded = this.onMouseEnter.bind(this); onMouseEnterBinded = this.onMouseEnter.bind(this);
onMouseLeaveBinded = this.onMouseLeave.bind(this); onMouseLeaveBinded = this.onMouseLeave.bind(this);
constructor(map: mapboxgl.Map, container: HTMLElement, popupOpen: { value: boolean }) { constructor(
map: maplibregl.Map,
layerEventManager: MapLayerEventManager,
container: HTMLElement,
popupOpen: { value: boolean }
) {
this.map = map; this.map = map;
this.layerEventManager = layerEventManager;
this.viewer = new Viewer({ this.viewer = new Viewer({
accessToken: 'MLY|4381405525255083|3204871ec181638c3c31320490f03011', accessToken: 'MLY|4381405525255083|3204871ec181638c3c31320490f03011',
@@ -61,15 +70,12 @@ export class MapillaryLayer {
}); });
const element = document.createElement('div'); const element = document.createElement('div');
element.className = 'mapboxgl-user-location mapboxgl-user-location-show-heading'; element.className = 'maplibregl-user-location maplibregl-user-location-show-heading';
const dot = document.createElement('div'); const dot = document.createElement('div');
dot.className = 'mapboxgl-user-location-dot'; dot.className = 'maplibregl-user-location-dot';
const heading = document.createElement('div');
heading.className = 'mapboxgl-user-location-heading';
element.appendChild(dot); element.appendChild(dot);
element.appendChild(heading);
this.marker = new mapboxgl.Marker({ this.marker = new maplibregl.Marker({
rotationAlignment: 'map', rotationAlignment: 'map',
element, element,
}); });
@@ -99,20 +105,20 @@ export class MapillaryLayer {
this.map.addSource('mapillary', mapillarySource); this.map.addSource('mapillary', mapillarySource);
} }
if (!this.map.getLayer('mapillary-sequence')) { if (!this.map.getLayer('mapillary-sequence')) {
this.map.addLayer(mapillarySequenceLayer); this.map.addLayer(mapillarySequenceLayer, ANCHOR_LAYER_KEY.mapillary);
} }
if (!this.map.getLayer('mapillary-image')) { if (!this.map.getLayer('mapillary-image')) {
this.map.addLayer(mapillaryImageLayer); this.map.addLayer(mapillaryImageLayer, ANCHOR_LAYER_KEY.mapillary);
} }
this.map.on('style.load', this.addBinded); this.map.on('style.load', this.addBinded);
this.map.on('mouseenter', 'mapillary-image', this.onMouseEnterBinded); this.layerEventManager.on('mouseenter', 'mapillary-image', this.onMouseEnterBinded);
this.map.on('mouseleave', 'mapillary-image', this.onMouseLeaveBinded); this.layerEventManager.on('mouseleave', 'mapillary-image', this.onMouseLeaveBinded);
} }
remove() { remove() {
this.map.off('style.load', this.addBinded); this.map.off('style.load', this.addBinded);
this.map.off('mouseenter', 'mapillary-image', this.onMouseEnterBinded); this.layerEventManager.off('mouseenter', 'mapillary-image', this.onMouseEnterBinded);
this.map.off('mouseleave', 'mapillary-image', this.onMouseLeaveBinded); this.layerEventManager.off('mouseleave', 'mapillary-image', this.onMouseLeaveBinded);
if (this.map.getLayer('mapillary-image')) { if (this.map.getLayer('mapillary-image')) {
this.map.removeLayer('mapillary-image'); this.map.removeLayer('mapillary-image');
@@ -134,7 +140,7 @@ export class MapillaryLayer {
this.popupOpen.value = false; this.popupOpen.value = false;
} }
onMouseEnter(e: mapboxgl.MapMouseEvent) { onMouseEnter(e: maplibregl.MapLayerMouseEvent) {
if ( if (
e.features && e.features &&
e.features.length > 0 && e.features.length > 0 &&

View File

@@ -0,0 +1,230 @@
import { settings } from '$lib/logic/settings';
import { get, type Writable } from 'svelte/store';
import {
basemaps,
defaultBasemap,
maptilerKeyPlaceHolder,
overlays,
terrainSources,
} from '$lib/assets/layers';
import { getLayers } from '$lib/components/map/layer-control/utils';
import { i18n } from '$lib/i18n.svelte';
const { currentBasemap, currentOverlays, customLayers, opacities, terrainSource } = settings;
const emptySource: maplibregl.GeoJSONSourceSpecification = {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [],
},
};
export const ANCHOR_LAYER_KEY = {
overlays: 'overlays-end',
mapillary: 'mapillary-end',
tracks: 'tracks-end',
directionMarkers: 'direction-markers-end',
distanceMarkers: 'distance-markers-end',
startEndMarkers: 'start-end-markers-end',
interactions: 'interactions-end',
overpass: 'overpass-end',
waypoints: 'waypoints-end',
};
const anchorLayers: maplibregl.LayerSpecification[] = Object.values(ANCHOR_LAYER_KEY).map((id) => ({
id: id,
type: 'symbol',
source: 'empty-source',
}));
export class StyleManager {
private _map: Writable<maplibregl.Map | null>;
private _maptilerKey: string;
private _pastOverlays: Set<string> = new Set();
constructor(map: Writable<maplibregl.Map | null>, maptilerKey: string) {
this._map = map;
this._maptilerKey = maptilerKey;
this._map.subscribe((map_) => {
if (map_) {
this.updateBasemap();
map_.on('style.load', () => this.updateOverlays());
map_.on('pitch', () => this.updateTerrain());
}
});
currentBasemap.subscribe(() => this.updateBasemap());
currentOverlays.subscribe(() => this.updateOverlays());
opacities.subscribe(() => this.updateOverlays());
terrainSource.subscribe(() => this.updateTerrain());
customLayers.subscribe(() => this.updateBasemap());
}
updateBasemap() {
const map_ = get(this._map);
if (!map_) return;
this.buildStyle().then((style) => map_.setStyle(style));
}
async buildStyle(): Promise<maplibregl.StyleSpecification> {
const custom = get(customLayers);
const style: maplibregl.StyleSpecification = {
version: 8,
projection: {
type: 'globe',
},
sources: {
'empty-source': emptySource,
},
layers: [],
};
let basemap = get(currentBasemap);
const basemapInfo = basemaps[basemap] ?? custom[basemap]?.value ?? basemaps[defaultBasemap];
const basemapStyle = await this.get(basemapInfo);
this.merge(style, basemapStyle);
const terrain = this.getCurrentTerrain();
style.sources[terrain.source] = terrainSources[terrain.source];
style.terrain = terrain.exaggeration > 0 ? terrain : undefined;
style.layers.push(...anchorLayers);
return style;
}
async updateOverlays() {
const map_ = get(this._map);
if (!map_) return;
if (!map_.getSource('empty-source')) return;
const custom = get(customLayers);
const overlayOpacities = get(opacities);
try {
const layers = getLayers(get(currentOverlays) ?? {});
for (let overlay in layers) {
if (!layers[overlay]) {
if (this._pastOverlays.has(overlay)) {
const overlayInfo = custom[overlay]?.value ?? overlays[overlay];
const overlayStyle = await this.get(overlayInfo);
for (let layer of overlayStyle.layers ?? []) {
if (map_.getLayer(layer.id)) {
map_.removeLayer(layer.id);
}
}
this._pastOverlays.delete(overlay);
}
} else {
const overlayInfo = custom[overlay]?.value ?? overlays[overlay];
const overlayStyle = await this.get(overlayInfo);
const opacity = overlayOpacities[overlay];
for (let sourceId in overlayStyle.sources) {
if (!map_.getSource(sourceId)) {
map_.addSource(sourceId, overlayStyle.sources[sourceId]);
}
}
for (let layer of overlayStyle.layers ?? []) {
if (!map_.getLayer(layer.id)) {
if (opacity !== undefined) {
if (layer.type === 'raster') {
if (!layer.paint) {
layer.paint = {};
}
layer.paint['raster-opacity'] = opacity;
} else if (layer.type === 'hillshade') {
if (!layer.paint) {
layer.paint = {};
}
layer.paint['hillshade-exaggeration'] = opacity / 2;
}
}
map_.addLayer(layer, ANCHOR_LAYER_KEY.overlays);
}
}
this._pastOverlays.add(overlay);
}
}
} catch (e) {}
}
updateTerrain() {
const map_ = get(this._map);
if (!map_) return;
const mapTerrain = map_.getTerrain();
const terrain = this.getCurrentTerrain();
if (JSON.stringify(mapTerrain) !== JSON.stringify(terrain)) {
if (terrain.exaggeration > 0) {
if (!map_.getSource(terrain.source)) {
map_.addSource(terrain.source, terrainSources[terrain.source]);
}
map_.setTerrain(terrain);
} else {
map_.setTerrain(null);
}
}
}
async get(
styleInfo: maplibregl.StyleSpecification | string
): Promise<maplibregl.StyleSpecification> {
if (typeof styleInfo === 'string') {
let styleUrl = styleInfo as string;
if (styleUrl.includes(maptilerKeyPlaceHolder)) {
styleUrl = styleUrl.replace(maptilerKeyPlaceHolder, this._maptilerKey);
}
const response = await fetch(styleUrl, { cache: 'force-cache' });
const style = await response.json();
return style;
} else {
return styleInfo;
}
}
merge(style: maplibregl.StyleSpecification, other: maplibregl.StyleSpecification) {
style.sources = { ...style.sources, ...other.sources };
for (let layer of other.layers ?? []) {
if (layer.type === 'symbol' && layer.layout && layer.layout['text-field']) {
const textField = layer.layout['text-field'];
if (
Array.isArray(textField) &&
textField.length >= 2 &&
textField[0] === 'coalesce' &&
Array.isArray(textField[1]) &&
textField[1][0] === 'get' &&
typeof textField[1][1] === 'string' &&
textField[1][1].startsWith('name')
) {
layer.layout['text-field'] = [
'coalesce',
['get', `name:${i18n.lang}`],
['get', 'name'],
];
}
}
style.layers.push(layer);
}
if (other.sprite && !style.sprite) {
style.sprite = other.sprite;
}
if (other.glyphs && !style.glyphs) {
style.glyphs = other.glyphs;
}
}
getCurrentTerrain() {
const terrain = get(terrainSource);
const source = terrainSources[terrain];
if (source.url && source.url.includes(maptilerKeyPlaceHolder)) {
source.url = source.url.replace(maptilerKeyPlaceHolder, this._maptilerKey);
}
const map_ = get(this._map);
return {
source: terrain,
exaggeration: !map_ || map_.getPitch() === 0 ? 0 : 1,
};
}
}

View File

@@ -11,7 +11,7 @@
import Clean from '$lib/components/toolbar/tools/Clean.svelte'; import Clean from '$lib/components/toolbar/tools/Clean.svelte';
import Reduce from '$lib/components/toolbar/tools/reduce/Reduce.svelte'; import Reduce from '$lib/components/toolbar/tools/reduce/Reduce.svelte';
import RoutingControlPopup from '$lib/components/toolbar/tools/routing/RoutingControlPopup.svelte'; import RoutingControlPopup from '$lib/components/toolbar/tools/routing/RoutingControlPopup.svelte';
import mapboxgl from 'mapbox-gl'; import maplibregl from 'maplibre-gl';
import { settings } from '$lib/logic/settings'; import { settings } from '$lib/logic/settings';
let { let {
@@ -23,11 +23,11 @@
const { minimizeRoutingMenu } = settings; const { minimizeRoutingMenu } = settings;
let popupElement: HTMLDivElement | undefined = $state(undefined); let popupElement: HTMLDivElement | undefined = $state(undefined);
let popup: mapboxgl.Popup | undefined = $derived.by(() => { let popup: maplibregl.Popup | undefined = $derived.by(() => {
if (!popupElement) { if (!popupElement) {
return undefined; return undefined;
} }
let popup = new mapboxgl.Popup({ let popup = new maplibregl.Popup({
closeButton: false, closeButton: false,
maxWidth: undefined, maxWidth: undefined,
}); });

View File

@@ -16,10 +16,11 @@
import { getURLForLanguage } from '$lib/utils'; import { getURLForLanguage } from '$lib/utils';
import { Trash2 } from '@lucide/svelte'; import { Trash2 } from '@lucide/svelte';
import { map } from '$lib/components/map/map'; import { map } from '$lib/components/map/map';
import type { GeoJSONSource } from 'mapbox-gl'; import type { GeoJSONSource } from 'maplibre-gl';
import { selection } from '$lib/logic/selection'; import { selection } from '$lib/logic/selection';
import { fileActions } from '$lib/logic/file-actions'; import { fileActions } from '$lib/logic/file-actions';
import { mapCursor, MapCursorState } from '$lib/logic/map-cursor'; import { mapCursor, MapCursorState } from '$lib/logic/map-cursor';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
let props: { let props: {
class?: string; class?: string;
@@ -28,7 +29,7 @@
let cleanType = $state(CleanType.INSIDE); let cleanType = $state(CleanType.INSIDE);
let deleteTrackpoints = $state(true); let deleteTrackpoints = $state(true);
let deleteWaypoints = $state(true); let deleteWaypoints = $state(true);
let rectangleCoordinates: mapboxgl.LngLat[] = $state([]); let rectangleCoordinates: maplibregl.LngLat[] = $state([]);
$effect(() => { $effect(() => {
if ($map) { if ($map) {
@@ -63,15 +64,18 @@
}); });
} }
if (!$map.getLayer('rectangle')) { if (!$map.getLayer('rectangle')) {
$map.addLayer({ $map.addLayer(
id: 'rectangle', {
type: 'fill', id: 'rectangle',
source: 'rectangle', type: 'fill',
paint: { source: 'rectangle',
'fill-color': 'SteelBlue', paint: {
'fill-opacity': 0.5, 'fill-color': 'SteelBlue',
'fill-opacity': 0.5,
},
}, },
}); ANCHOR_LAYER_KEY.interactions
);
} }
} }
} }

View File

@@ -2,7 +2,6 @@
import { Button } from '$lib/components/ui/button'; import { Button } from '$lib/components/ui/button';
import Help from '$lib/components/Help.svelte'; import Help from '$lib/components/Help.svelte';
import { MountainSnow } from '@lucide/svelte'; import { MountainSnow } from '@lucide/svelte';
import { map } from '$lib/components/map/map';
import { i18n } from '$lib/i18n.svelte'; import { i18n } from '$lib/i18n.svelte';
import { getURLForLanguage } from '$lib/utils'; import { getURLForLanguage } from '$lib/utils';
import { selection } from '$lib/logic/selection'; import { selection } from '$lib/logic/selection';
@@ -20,11 +19,7 @@
variant="outline" variant="outline"
class="whitespace-normal h-fit" class="whitespace-normal h-fit"
disabled={!validSelection} disabled={!validSelection}
onclick={() => { onclick={() => fileActions.addElevationToSelection()}
if ($map) {
fileActions.addElevationToSelection($map);
}
}}
> >
<MountainSnow size="16" class="shrink-0" /> <MountainSnow size="16" class="shrink-0" />
{i18n._('toolbar.elevation.button')} {i18n._('toolbar.elevation.button')}

View File

@@ -1,10 +1,11 @@
import { ListItem, ListTrackSegmentItem } from '$lib/components/file-list/file-list'; import { ListItem, ListTrackSegmentItem } from '$lib/components/file-list/file-list';
import { map } from '$lib/components/map/map'; import { map } from '$lib/components/map/map';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
import { fileActions } from '$lib/logic/file-actions'; import { fileActions } from '$lib/logic/file-actions';
import { GPXFileStateCollectionObserver, type GPXFileState } from '$lib/logic/file-state'; import { GPXFileStateCollectionObserver, type GPXFileState } from '$lib/logic/file-state';
import { selection } from '$lib/logic/selection'; import { selection } from '$lib/logic/selection';
import { ramerDouglasPeucker, TrackPoint, type SimplifiedTrackPoint } from 'gpx'; import { ramerDouglasPeucker, TrackPoint, type SimplifiedTrackPoint } from 'gpx';
import type { GeoJSONSource } from 'mapbox-gl'; import type { GeoJSONSource } from 'maplibre-gl';
import { get, writable } from 'svelte/store'; import { get, writable } from 'svelte/store';
export const minTolerance = 0.1; export const minTolerance = 0.1;
@@ -28,17 +29,15 @@ export class ReducedGPXLayer {
update() { update() {
const file = this._fileState.file; const file = this._fileState.file;
const stats = this._fileState.statistics; if (!file) {
if (!file || !stats) {
return; return;
} }
file.forEachSegment((segment, trackIndex, segmentIndex) => { file.forEachSegment((segment, trackIndex, segmentIndex) => {
let segmentItem = new ListTrackSegmentItem(file._data.id, trackIndex, segmentIndex); let segmentItem = new ListTrackSegmentItem(file._data.id, trackIndex, segmentIndex);
let statistics = stats.getStatisticsFor(segmentItem);
this._updateSimplified(segmentItem.getFullId(), [ this._updateSimplified(segmentItem.getFullId(), [
segmentItem, segmentItem,
statistics.local.points.length, segment.trkpt.length,
ramerDouglasPeucker(statistics.local.points, minTolerance), ramerDouglasPeucker(segment.trkpt, minTolerance),
]); ]);
}); });
} }
@@ -146,17 +145,18 @@ export class ReducedGPXLayerCollection {
}); });
} }
if (!map_.getLayer('simplified')) { if (!map_.getLayer('simplified')) {
map_.addLayer({ map_.addLayer(
id: 'simplified', {
type: 'line', id: 'simplified',
source: 'simplified', type: 'line',
paint: { source: 'simplified',
'line-color': 'white', paint: {
'line-width': 3, 'line-color': 'white',
'line-width': 3,
},
}, },
}); ANCHOR_LAYER_KEY.interactions
} else { );
map_.moveLayer('simplified');
} }
} }

View File

@@ -21,7 +21,7 @@
SquareArrowUpLeft, SquareArrowUpLeft,
SquareArrowOutDownRight, SquareArrowOutDownRight,
} from '@lucide/svelte'; } from '@lucide/svelte';
import { brouterProfiles } from '$lib/components/toolbar/tools/routing/routing'; import { routingProfiles } from '$lib/components/toolbar/tools/routing/routing';
import { i18n } from '$lib/i18n.svelte'; import { i18n } from '$lib/i18n.svelte';
import { slide } from 'svelte/transition'; import { slide } from 'svelte/transition';
import { import {
@@ -51,7 +51,7 @@
}: { }: {
minimized?: boolean; minimized?: boolean;
minimizable?: boolean; minimizable?: boolean;
popup?: mapboxgl.Popup; popup?: maplibregl.Popup;
popupElement?: HTMLDivElement; popupElement?: HTMLDivElement;
class?: string; class?: string;
} = $props(); } = $props();
@@ -167,7 +167,7 @@
{i18n._(`toolbar.routing.activities.${$routingProfile}`)} {i18n._(`toolbar.routing.activities.${$routingProfile}`)}
</Select.Trigger> </Select.Trigger>
<Select.Content> <Select.Content>
{#each Object.keys(brouterProfiles) as profile} {#each Object.keys(routingProfiles) as profile}
<Select.Item value={profile} <Select.Item value={profile}
>{i18n._( >{i18n._(
`toolbar.routing.activities.${profile}` `toolbar.routing.activities.${profile}`

View File

@@ -1,6 +1,6 @@
import { distance, type Coordinates, TrackPoint, TrackSegment, Track, projectedPoint } from 'gpx'; import { distance, type Coordinates, TrackPoint, TrackSegment, Track, projectedPoint } from 'gpx';
import { get, writable, type Readable } from 'svelte/store'; import { get, writable, type Readable } from 'svelte/store';
import mapboxgl from 'mapbox-gl'; import maplibregl from 'maplibre-gl';
import { route } from './routing'; import { route } from './routing';
import { toast } from 'svelte-sonner'; import { toast } from 'svelte-sonner';
import { import {
@@ -32,7 +32,7 @@ export class RoutingControls {
file: Readable<GPXFileWithStatistics | undefined>; file: Readable<GPXFileWithStatistics | undefined>;
anchors: AnchorWithMarker[] = []; anchors: AnchorWithMarker[] = [];
shownAnchors: AnchorWithMarker[] = []; shownAnchors: AnchorWithMarker[] = [];
popup: mapboxgl.Popup; popup: maplibregl.Popup;
popupElement: HTMLElement; popupElement: HTMLElement;
temporaryAnchor: AnchorWithMarker; temporaryAnchor: AnchorWithMarker;
lastDragEvent = 0; lastDragEvent = 0;
@@ -43,12 +43,12 @@ export class RoutingControls {
this.toggleAnchorsForZoomLevelAndBounds.bind(this); this.toggleAnchorsForZoomLevelAndBounds.bind(this);
showTemporaryAnchorBinded: (e: any) => void = this.showTemporaryAnchor.bind(this); showTemporaryAnchorBinded: (e: any) => void = this.showTemporaryAnchor.bind(this);
updateTemporaryAnchorBinded: (e: any) => void = this.updateTemporaryAnchor.bind(this); updateTemporaryAnchorBinded: (e: any) => void = this.updateTemporaryAnchor.bind(this);
appendAnchorBinded: (e: mapboxgl.MapMouseEvent) => void = this.appendAnchor.bind(this); appendAnchorBinded: (e: maplibregl.MapMouseEvent) => void = this.appendAnchor.bind(this);
constructor( constructor(
fileId: string, fileId: string,
file: Readable<GPXFileWithStatistics | undefined>, file: Readable<GPXFileWithStatistics | undefined>,
popup: mapboxgl.Popup, popup: maplibregl.Popup,
popupElement: HTMLElement popupElement: HTMLElement
) { ) {
this.fileId = fileId; this.fileId = fileId;
@@ -94,7 +94,8 @@ export class RoutingControls {
add() { add() {
const map_ = get(map); const map_ = get(map);
if (!map_) { const layerEventManager = map.layerEventManager;
if (!map_ || !layerEventManager) {
return; return;
} }
@@ -102,8 +103,8 @@ export class RoutingControls {
map_.on('move', this.toggleAnchorsForZoomLevelAndBoundsBinded); map_.on('move', this.toggleAnchorsForZoomLevelAndBoundsBinded);
map_.on('click', this.appendAnchorBinded); map_.on('click', this.appendAnchorBinded);
map_.on('mousemove', this.fileId, this.showTemporaryAnchorBinded); layerEventManager.on('mousemove', this.fileId, this.showTemporaryAnchorBinded);
map_.on('click', this.fileId, stopPropagation); layerEventManager.on('click', this.fileId, stopPropagation);
this.fileUnsubscribe = this.file.subscribe(this.updateControls.bind(this)); this.fileUnsubscribe = this.file.subscribe(this.updateControls.bind(this));
} }
@@ -152,20 +153,18 @@ export class RoutingControls {
remove() { remove() {
const map_ = get(map); const map_ = get(map);
if (!map_) { const layerEventManager = map.layerEventManager;
return;
}
this.active = false; this.active = false;
for (let anchor of this.anchors) { for (let anchor of this.anchors) {
anchor.marker.remove(); anchor.marker.remove();
} }
map_.off('move', this.toggleAnchorsForZoomLevelAndBoundsBinded); map_?.off('move', this.toggleAnchorsForZoomLevelAndBoundsBinded);
map_.off('click', this.appendAnchorBinded); map_?.off('click', this.appendAnchorBinded);
map_.off('mousemove', this.fileId, this.showTemporaryAnchorBinded); layerEventManager?.off('mousemove', this.fileId, this.showTemporaryAnchorBinded);
map_.off('click', this.fileId, stopPropagation); layerEventManager?.off('click', this.fileId, stopPropagation);
map_.off('mousemove', this.updateTemporaryAnchorBinded); map_?.off('mousemove', this.updateTemporaryAnchorBinded);
this.temporaryAnchor.marker.remove(); this.temporaryAnchor.marker.remove();
this.fileUnsubscribe(); this.fileUnsubscribe();
@@ -180,7 +179,7 @@ export class RoutingControls {
let element = document.createElement('div'); let element = document.createElement('div');
element.className = `h-5 w-5 xs:h-4 xs:w-4 md:h-3 md:w-3 rounded-full bg-white border-2 border-black cursor-pointer`; element.className = `h-5 w-5 xs:h-4 xs:w-4 md:h-3 md:w-3 rounded-full bg-white border-2 border-black cursor-pointer`;
let marker = new mapboxgl.Marker({ let marker = new maplibregl.Marker({
draggable: true, draggable: true,
className: 'z-10', className: 'z-10',
element, element,
@@ -215,7 +214,7 @@ export class RoutingControls {
return anchor; return anchor;
} }
handleClickForAnchor(anchor: Anchor, marker: mapboxgl.Marker) { handleClickForAnchor(anchor: Anchor, marker: maplibregl.Marker) {
return (e: any) => { return (e: any) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
@@ -607,7 +606,7 @@ export class RoutingControls {
}); });
} }
async appendAnchor(e: mapboxgl.MapMouseEvent) { async appendAnchor(e: maplibregl.MapMouseEvent) {
// Add a new anchor to the end of the last segment // Add a new anchor to the end of the last segment
if (get(streetViewEnabled) && get(streetViewSource) === 'google') { if (get(streetViewEnabled) && get(streetViewSource) === 'google') {
return; return;
@@ -793,24 +792,25 @@ export class RoutingControls {
replacingDistance += replacingDistance +=
distance(response[i - 1].getCoordinates(), response[i].getCoordinates()) / 1000; distance(response[i - 1].getCoordinates(), response[i].getCoordinates()) / 1000;
} }
let startAnchorStats = stats.getTrackPoint(anchors[0].point._data.index)!;
let endAnchorStats = stats.getTrackPoint(
anchors[anchors.length - 1].point._data.index
)!;
let replacedDistance = let replacedDistance =
stats.local.distance.moving[anchors[anchors.length - 1].point._data.index] - endAnchorStats.distance.moving - startAnchorStats.distance.moving;
stats.local.distance.moving[anchors[0].point._data.index];
let newDistance = stats.global.distance.moving + replacingDistance - replacedDistance; let newDistance = stats.global.distance.moving + replacingDistance - replacedDistance;
let newTime = (newDistance / stats.global.speed.moving) * 3600; let newTime = (newDistance / stats.global.speed.moving) * 3600;
let remainingTime = let remainingTime =
stats.global.time.moving - stats.global.time.moving -
(stats.local.time.moving[anchors[anchors.length - 1].point._data.index] - (endAnchorStats.time.moving - startAnchorStats.time.moving);
stats.local.time.moving[anchors[0].point._data.index]);
let replacingTime = newTime - remainingTime; let replacingTime = newTime - remainingTime;
if (replacingTime <= 0) { if (replacingTime <= 0) {
// Fallback to simple time difference // Fallback to simple time difference
replacingTime = replacingTime = endAnchorStats.time.total - startAnchorStats.time.total;
stats.local.time.total[anchors[anchors.length - 1].point._data.index] -
stats.local.time.total[anchors[0].point._data.index];
} }
speed = (replacingDistance / replacingTime) * 3600; speed = (replacingDistance / replacingTime) * 3600;
@@ -820,9 +820,7 @@ export class RoutingControls {
let endIndex = anchors[anchors.length - 1].point._data.index; let endIndex = anchors[anchors.length - 1].point._data.index;
startTime = new Date( startTime = new Date(
(segment.trkpt[endIndex].time?.getTime() ?? 0) - (segment.trkpt[endIndex].time?.getTime() ?? 0) -
(replacingTime + (replacingTime + endAnchorStats.time.total - endAnchorStats.time.moving) *
stats.local.time.total[endIndex] -
stats.local.time.moving[endIndex]) *
1000 1000
); );
} }
@@ -859,6 +857,6 @@ type Anchor = {
}; };
type AnchorWithMarker = Anchor & { type AnchorWithMarker = Anchor & {
marker: mapboxgl.Marker; marker: maplibregl.Marker;
inZoom: boolean; inZoom: boolean;
}; };

View File

@@ -6,7 +6,7 @@ import { get } from 'svelte/store';
const { routing, routingProfile, privateRoads } = settings; const { routing, routingProfile, privateRoads } = settings;
export const brouterProfiles: { [key: string]: string } = { export const routingProfiles: { [key: string]: string } = {
bike: 'Trekking-dry', bike: 'Trekking-dry',
racing_bike: 'fastbike', racing_bike: 'fastbike',
gravel_bike: 'gravel', gravel_bike: 'gravel',
@@ -19,7 +19,7 @@ export const brouterProfiles: { [key: string]: string } = {
export function route(points: Coordinates[]): Promise<TrackPoint[]> { export function route(points: Coordinates[]): Promise<TrackPoint[]> {
if (get(routing)) { if (get(routing)) {
return getRoute(points, brouterProfiles[get(routingProfile)], get(privateRoads)); return getRoute(points, routingProfiles[get(routingProfile)], get(privateRoads));
} else { } else {
return getIntermediatePoints(points); return getIntermediatePoints(points);
} }

View File

@@ -26,26 +26,24 @@
let validSelection = $derived( let validSelection = $derived(
$selection.hasAnyChildren(new ListRootItem(), true, ['waypoints']) && $selection.hasAnyChildren(new ListRootItem(), true, ['waypoints']) &&
$gpxStatistics.local.points.length > 0 $gpxStatistics.global.length > 0
); );
let maxSliderValue = $derived( let maxSliderValue = $derived(
validSelection && $gpxStatistics.local.points.length > 0 validSelection && $gpxStatistics.global.length > 0 ? $gpxStatistics.global.length - 1 : 1
? $gpxStatistics.local.points.length - 1
: 1
); );
let sliderValues = $derived([0, maxSliderValue]); let sliderValues = $derived([0, maxSliderValue]);
let canCrop = $derived(sliderValues[0] != 0 || sliderValues[1] != maxSliderValue); let canCrop = $derived(sliderValues[0] != 0 || sliderValues[1] != maxSliderValue);
onMount(() => { onMount(() => {
if ($map) { if ($map) {
splitControls = new SplitControls($map); splitControls = new SplitControls($map, map.layerEventManager!);
} }
}); });
function updateSlicedGPXStatistics() { function updateSlicedGPXStatistics() {
if (validSelection && canCrop) { if (validSelection && canCrop) {
$slicedGPXStatistics = [ $slicedGPXStatistics = [
get(gpxStatistics).slice(sliderValues[0], sliderValues[1]), get(gpxStatistics).sliced(sliderValues[0], sliderValues[1]),
sliderValues[0], sliderValues[0],
sliderValues[1], sliderValues[1],
]; ];

View File

@@ -8,39 +8,33 @@ import { get } from 'svelte/store';
import { fileStateCollection } from '$lib/logic/file-state'; import { fileStateCollection } from '$lib/logic/file-state';
import { fileActions } from '$lib/logic/file-actions'; import { fileActions } from '$lib/logic/file-actions';
import { mapCursor, MapCursorState } from '$lib/logic/map-cursor'; import { mapCursor, MapCursorState } from '$lib/logic/map-cursor';
import type { GeoJSONSource } from 'maplibre-gl';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
import type { MapLayerEventManager } from '$lib/components/map/map-layer-event-manager';
import { loadSVGIcon } from '$lib/utils';
export class SplitControls { export class SplitControls {
map: mapboxgl.Map; map: maplibregl.Map;
layerEventManager: MapLayerEventManager;
unsubscribes: Function[] = []; unsubscribes: Function[] = [];
layerOnMouseEnterBinded: (e: any) => void = this.layerOnMouseEnter.bind(this); layerOnMouseEnterBinded: (e: any) => void = this.layerOnMouseEnter.bind(this);
layerOnMouseLeaveBinded: () => void = this.layerOnMouseLeave.bind(this); layerOnMouseLeaveBinded: () => void = this.layerOnMouseLeave.bind(this);
layerOnClickBinded: (e: any) => void = this.layerOnClick.bind(this); layerOnClickBinded: (e: any) => void = this.layerOnClick.bind(this);
constructor(map: mapboxgl.Map) { constructor(map: maplibregl.Map, layerEventManager: MapLayerEventManager) {
this.map = map; this.map = map;
this.layerEventManager = layerEventManager;
if (!this.map.hasImage('split-control')) { loadSVGIcon(
let icon = new Image(100, 100); this.map,
icon.onload = () => { 'split-control',
if (!this.map.hasImage('split-control')) { `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">
this.map.addImage('split-control', icon); <circle cx="20" cy="20" r="20" fill="white" />
} <g transform="translate(8 8)">
}; ${Scissors.replace('stroke="currentColor"', 'stroke="black"')}
</g>
// Lucide icons are SVG files with a 24x24 viewBox </svg>`
// Create a new SVG with a 32x32 viewBox and center the icon in a circle );
icon.src =
'data:image/svg+xml,' +
encodeURIComponent(`
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">
<circle cx="20" cy="20" r="20" fill="white" />
<g transform="translate(8 8)">
${Scissors.replace('stroke="currentColor"', 'stroke="black"')}
</g>
</svg>
`);
}
this.unsubscribes.push(gpxStatistics.subscribe(this.addIfNeeded.bind(this))); this.unsubscribes.push(gpxStatistics.subscribe(this.addIfNeeded.bind(this)));
this.unsubscribes.push(currentTool.subscribe(this.addIfNeeded.bind(this))); this.unsubscribes.push(currentTool.subscribe(this.addIfNeeded.bind(this)));
@@ -97,7 +91,7 @@ export class SplitControls {
}, false); }, false);
try { try {
let source = this.map.getSource('split-controls') as mapboxgl.GeoJSONSource | undefined; let source = this.map.getSource('split-controls') as GeoJSONSource | undefined;
if (source) { if (source) {
source.setData(data); source.setData(data);
} else { } else {
@@ -108,33 +102,42 @@ export class SplitControls {
} }
if (!this.map.getLayer('split-controls')) { if (!this.map.getLayer('split-controls')) {
this.map.addLayer({ this.map.addLayer(
id: 'split-controls', {
type: 'symbol', id: 'split-controls',
source: 'split-controls', type: 'symbol',
layout: { source: 'split-controls',
'icon-image': 'split-control', layout: {
'icon-size': 0.25, 'icon-image': 'split-control',
'icon-padding': 0, 'icon-size': 0.25,
'icon-padding': 0,
},
filter: ['<=', ['get', 'minZoom'], ['zoom']],
}, },
filter: ['<=', ['get', 'minZoom'], ['zoom']], ANCHOR_LAYER_KEY.interactions
}); );
this.map.on('mouseenter', 'split-controls', this.layerOnMouseEnterBinded); this.layerEventManager.on(
this.map.on('mouseleave', 'split-controls', this.layerOnMouseLeaveBinded); 'mouseenter',
this.map.on('click', 'split-controls', this.layerOnClickBinded); 'split-controls',
this.layerOnMouseEnterBinded
);
this.layerEventManager.on(
'mouseleave',
'split-controls',
this.layerOnMouseLeaveBinded
);
this.layerEventManager.on('click', 'split-controls', this.layerOnClickBinded);
} }
this.map.moveLayer('split-controls');
} catch (e) { } catch (e) {
// No reliable way to check if the map is ready to add sources and layers // No reliable way to check if the map is ready to add sources and layers
} }
} }
remove() { remove() {
this.map.off('mouseenter', 'split-controls', this.layerOnMouseEnterBinded); this.layerEventManager.off('mouseenter', 'split-controls', this.layerOnMouseEnterBinded);
this.map.off('mouseleave', 'split-controls', this.layerOnMouseLeaveBinded); this.layerEventManager.off('mouseleave', 'split-controls', this.layerOnMouseLeaveBinded);
this.map.off('click', 'split-controls', this.layerOnClickBinded); this.layerEventManager.off('click', 'split-controls', this.layerOnClickBinded);
try { try {
if (this.map.getLayer('split-controls')) { if (this.map.getLayer('split-controls')) {
@@ -157,7 +160,7 @@ export class SplitControls {
mapCursor.notify(MapCursorState.SPLIT_CONTROL, false); mapCursor.notify(MapCursorState.SPLIT_CONTROL, false);
} }
layerOnClick(e: mapboxgl.MapMouseEvent) { layerOnClick(e: maplibregl.MapLayerMouseEvent) {
let coordinates = (e.features![0].geometry as GeoJSON.Point).coordinates; let coordinates = (e.features![0].geometry as GeoJSON.Point).coordinates;
fileActions.split( fileActions.split(
get(splitAs), get(splitAs),

View File

@@ -16,7 +16,7 @@
import { fileActions } from '$lib/logic/file-actions'; import { fileActions } from '$lib/logic/file-actions';
import { map } from '$lib/components/map/map'; import { map } from '$lib/components/map/map';
import { mapCursor, MapCursorState } from '$lib/logic/map-cursor'; import { mapCursor, MapCursorState } from '$lib/logic/map-cursor';
import mapboxgl from 'mapbox-gl'; import maplibregl from 'maplibre-gl';
import { getSvgForSymbol } from '$lib/components/map/gpx-layer/gpx-layer'; import { getSvgForSymbol } from '$lib/components/map/gpx-layer/gpx-layer';
let props: { let props: {
@@ -41,7 +41,7 @@
}) })
); );
let marker: mapboxgl.Marker | null = null; let marker: maplibregl.Marker | null = null;
function reset() { function reset() {
if ($selectedWaypoint) { if ($selectedWaypoint) {
@@ -125,7 +125,7 @@
let element = document.createElement('div'); let element = document.createElement('div');
element.classList.add('w-8', 'h-8'); element.classList.add('w-8', 'h-8');
element.innerHTML = getSvgForSymbol(symbolKey); element.innerHTML = getSvgForSymbol(symbolKey);
marker = new mapboxgl.Marker({ marker = new maplibregl.Marker({
element, element,
anchor: 'bottom', anchor: 'bottom',
}) })

View File

@@ -1,5 +1,5 @@
Mapbox ist das Unternehmen, das einige der schönen Karten auf dieser Website zur Verfügung stellt. Mapbox ist das Unternehmen, das einige der schönen Karten auf dieser Website zur Verfügung stellt.
Sie entwickeln auch die <a href="https://github.com/mapbox/mapbox-gl-js" target="_blank">Karten-Engine</a> welche **gpx.studio** unterstützt. Sie entwickeln auch die <a href="https://github.com/mapbox/mapbox-gl-js" target="_blank">Karten-Engine</a> welche **gpx.studio** unterstützt.
Wir sind äusserst glücklich und dankbar, Teil ihres <a href="https://mapbox.com/community" target="_blank">Community</a> Programms zu sein, das gemeinnützige Organisationen, Bildungseinrichtungen und Organisationen mit positivem Einfluss unterstützt. Wir sind äußerst glücklich und dankbar, Teil ihres <a href="https://mapbox.com/community" target="_blank">Community</a> Programms zu sein, das gemeinnützige Organisationen, Bildungseinrichtungen und Organisationen mit positivem Einfluss unterstützt.
Diese Partnerschaft ermöglicht es **gpx.studio**, von den Mapbox-Tools zu ermäßigten Preisen zu profitieren, was erheblich zur finanziellen Tragfähigkeit des Projekts beiträgt und es uns ermöglicht, die bestmögliche Benutzererfahrung zu bieten. Diese Partnerschaft ermöglicht es **gpx.studio**, von den Mapbox-Tools zu ermäßigten Preisen zu profitieren, was erheblich zur finanziellen Tragfähigkeit des Projekts beiträgt und es uns ermöglicht, die bestmögliche Benutzererfahrung zu bieten.

View File

@@ -12,6 +12,7 @@ title: Files and statistics
let gpxStatistics = writable(exampleGPXFile.getStatistics()); let gpxStatistics = writable(exampleGPXFile.getStatistics());
let slicedGPXStatistics = writable(undefined); let slicedGPXStatistics = writable(undefined);
let hoveredPoint = writable(null);
let additionalDatasets = writable(['speed', 'atemp']); let additionalDatasets = writable(['speed', 'atemp']);
let elevationFill = writable(undefined); let elevationFill = writable(undefined);
</script> </script>
@@ -84,6 +85,7 @@ You can also use the mouse wheel to zoom in and out on the elevation profile, an
<ElevationProfile <ElevationProfile
{gpxStatistics} {gpxStatistics}
{slicedGPXStatistics} {slicedGPXStatistics}
{hoveredPoint}
{additionalDatasets} {additionalDatasets}
{elevationFill} {elevationFill}
/> />

View File

@@ -5,7 +5,7 @@
## <HeartHandshake size="18" class="inline-block align-baseline" /> Help keep the website free (and ad-free) ## <HeartHandshake size="18" class="inline-block align-baseline" /> Help keep the website free (and ad-free)
Each time you add or move GPS points, our servers calculate the best route on the road network. Each time you add or move GPS points, our servers calculate the best route on the road network.
We also use APIs from <a href="https://mapbox.com" target="_blank">Mapbox</a> to display beautiful maps, retrieve elevation data and allow you to search for places. We also use APIs from <a href="https://maptiler.com" target="_blank">MapTiler</a> to display beautiful maps, retrieve elevation data and allow you to search for places.
Unfortunately, this is expensive. Unfortunately, this is expensive.
If you enjoy using this tool and find it valuable, please consider making a small donation to help keep the website free and ad-free. If you enjoy using this tool and find it valuable, please consider making a small donation to help keep the website free and ad-free.

View File

@@ -1,5 +0,0 @@
Mapbox is the company that provides some of the beautiful maps on this website.
They also develop the <a href="https://github.com/mapbox/mapbox-gl-js" target="_blank">map engine</a> which powers **gpx.studio**.
We are incredibly fortunate and grateful to be part of their <a href="https://mapbox.com/community" target="_blank">Community</a> program, which supports nonprofits, educational institutions, and positive impact organizations.
This partnership allows **gpx.studio** to benefit from Mapbox tools at discounted prices, greatly contributing to the financial viability of the project and enabling us to offer the best possible user experience.

View File

@@ -0,0 +1,2 @@
MapTiler is the company that provides some of the beautiful maps on this website.
This partnership allows **gpx.studio** to benefit from MapTiler tools at discounted prices, greatly contributing to the financial viability of the project and enabling us to offer the best possible user experience.

View File

@@ -12,7 +12,7 @@ title: Integration
You can use **gpx.studio** to create maps showing your GPX files and embed them in your website. You can use **gpx.studio** to create maps showing your GPX files and embed them in your website.
All you need is: All you need is:
1. A <a href="https://account.mapbox.com/auth/signup" target="_blank">Mapbox access token</a> to load the map, and 1. A <a href="https://cloud.maptiler.com/auth/widget?next=https://cloud.maptiler.com/maps/" target="_blank">MapTiler key</a> to load the map, and
1. GPX files hosted on your server or on Google Drive, or accessible via a public URL. 1. GPX files hosted on your server or on Google Drive, or accessible via a public URL.
You can then play with the configurator below to customize your map and generate the corresponding HTML code. You can then play with the configurator below to customize your map and generate the corresponding HTML code.

View File

@@ -58,7 +58,7 @@ Only one basemap can be displayed at a time.
<div class="flex flex-col items-center"> <div class="flex flex-col items-center">
<DocsLayers /> <DocsLayers />
<span class="text-sm text-center mt-2"> <span class="text-sm text-center mt-2">
Hover over the map to show the <a href="https://hiking.waymarkedtrails.org" target="_blank">Waymarked Trails hiking</a> overlay on top of the <a href="https://www.mapbox.com/maps/outdoors" target="_blank">Mapbox Outdoors</a> basemap. Hover over the map to show the <a href="https://hiking.waymarkedtrails.org" target="_blank">Waymarked Trails hiking</a> overlay on top of the <a href="https://www.maptiler.com/maps/outdoor-topo/" target="_blank">MapTiler Topo</a> basemap.
</span> </span>
</div> </div>
@@ -67,4 +67,4 @@ They can be enabled in the [map layer settings dialog](./menu/settings).
In these settings, you can also manage the opacity of the overlays. In these settings, you can also manage the opacity of the overlays.
For advanced users, it is possible to add custom basemaps and overlays by providing <a href="https://en.wikipedia.org/wiki/Web_Map_Tile_Service" target="_blank">WMTS</a>, <a href="https://en.wikipedia.org/wiki/Web_Map_Service" target="_blank">WMS</a>, or <a href="https://docs.mapbox.com/help/glossary/style/" target="_blank">Mapbox style JSON</a> URLs. For advanced users, it is possible to add custom basemaps and overlays by providing <a href="https://en.wikipedia.org/wiki/Web_Map_Tile_Service" target="_blank">WMTS</a>, <a href="https://en.wikipedia.org/wiki/Web_Map_Service" target="_blank">WMS</a>, or <a href="https://maplibre.org/maplibre-style-spec/" target="_blank">MapLibre style JSON</a> URLs.

View File

@@ -18,7 +18,7 @@ This tool allows you to add elevation data to traces and [points of interest](..
<DocsNote> <DocsNote>
Elevation data is provided by <a href="https://mapbox.com" target="_blank">Mapbox</a>. Elevation data is provided by <a href="https://maptiler.com" target="_blank">MapTiler</a>.
You can learn more about its origin and accuracy in the <a href="https://docs.mapbox.com/data/tilesets/reference/mapbox-terrain-dem-v1/#elevation-data" target="_blank">documentation</a>. You can learn more about its origin and accuracy in the <a href="https://docs.maptiler.com/guides/map-tiling-hosting/data-hosting/rgb-terrain-by-maptiler/" target="_blank">documentation</a>.
</DocsNote> </DocsNote>

View File

@@ -50,7 +50,7 @@ Facendo clic destro su una scheda file, è possibile accedere alle stesse azioni
Come accennato nella [sezione opzioni di visualizzazione](./menu/view), è possibile passare a un layout ad albero per l'elenco dei file. Come accennato nella [sezione opzioni di visualizzazione](./menu/view), è possibile passare a un layout ad albero per l'elenco dei file.
Questo layout è ideale per gestire un gran numero di file aperti, organizzandoli in una lista verticale sul lato destro della mappa. Questo layout è ideale per gestire un gran numero di file aperti, organizzandoli in una lista verticale sul lato destro della mappa.
Inoltre, la vista ad albero dei file consente di ispezionare [tracce, segmenti e punti di interesse](./gpx) all'interno dei file attraverso sezioni espandibili. Inoltre, la vista ad albero dei file consente d'ispezionare [tracce, segmenti e punti di interesse](./gpx) all'interno dei file attraverso sezioni espandibili.
Puoi anche applicare [modifiche](./menu/edit) e [strumenti](./toolbar) agli elementi interni del file. Puoi anche applicare [modifiche](./menu/edit) e [strumenti](./toolbar) agli elementi interni del file.
Inoltre, è possibile trascinare e rilasciare gli elementi per riordinarli, o spostarli nella gerarchia o anche in un altro file. Inoltre, è possibile trascinare e rilasciare gli elementi per riordinarli, o spostarli nella gerarchia o anche in un altro file.
@@ -78,7 +78,7 @@ Quando si passa sopra il profilo di elevazione, un suggerimento mostrerà le sta
Per ottenere le statistiche per una sezione specifica del profilo di elevazione, è possibile trascinare un rettangolo di selezione sul profilo. Per ottenere le statistiche per una sezione specifica del profilo di elevazione, è possibile trascinare un rettangolo di selezione sul profilo.
Fare clic sul profilo per resettare la selezione. Fare clic sul profilo per resettare la selezione.
È inoltre possibile utilizzare la rotellina del mouse per ingrandire e rimpicciolire sul profilo di elevazione, e spostarsi a sinistra e a destra trascinando il profilo tenendo premuto il tasto <kbd>Maiusc</kbd>. È inoltre possibile utilizzare la rotellina del mouse per ingrandire e rimpicciolire sul profilo di elevazione, e spostarsi a sinistra e a destra trascinando il profilo tenendo premuto il tasto <kbd>Maiuscolo</kbd>.
<div class="h-48 w-full"> <div class="h-48 w-full">
<ElevationProfile <ElevationProfile

View File

@@ -21,7 +21,7 @@ Queste sono organizzate in una struttura gerarchica, con le tracce stesse al liv
- Una **traccia** è composta da una sequenza di segmenti scollegati. - Una **traccia** è composta da una sequenza di segmenti scollegati.
Inoltre, può contenere metadati come un **nome**, una **descrizione**, e **proprietà di visualizzazione**. Inoltre, può contenere metadati come un **nome**, una **descrizione**, e **proprietà di visualizzazione**.
- Un **segmento** è una sequenza di punti GPS che formano un percorso continuo. - Un **segmento** è una sequenza di punti GPS che formano un percorso continuo.
- Un **punto GPS** è una posizione con una latitudine, una longitudine, ed eventualmente un timestamp e un'altitudine. - Un **punto GPS** è una posizione con una latitudine, una longitudine, ed eventualmente una marcatura temporale e un'altitudine.
Alcuni dispositivi memorizzano anche informazioni aggiuntive come frequenza cardiaca, cadenza, temperatura e potenza. Alcuni dispositivi memorizzano anche informazioni aggiuntive come frequenza cardiaca, cadenza, temperatura e potenza.
Nella maggior parte dei casi, i file GPX contengono una singola traccia con un singolo segmento. Nella maggior parte dei casi, i file GPX contengono una singola traccia con un singolo segmento.

View File

@@ -5,9 +5,9 @@
## <HeartHandshake size="18" class="inline-block align-baseline" /> Aiuta a mantenere il sito gratuito (e senza pubblicità) ## <HeartHandshake size="18" class="inline-block align-baseline" /> Aiuta a mantenere il sito gratuito (e senza pubblicità)
Ogni volta che aggiungi o sposti i punti GPS, i nostri server calcolano il percorso migliore sulla rete stradale. Ogni volta che aggiungi o sposti i punti GPS, i nostri server calcolano il percorso migliore sulla rete stradale.
Utilizziamo anche le API di <a href="https://mapbox.com" target="_blank">Mapbox</a> per visualizzare mappe gradevoli, recuperare i dati altimetrici e consentire la ricerca di luoghi. Utilizziamo anche le API di <a href="https://mapbox.com" target="_blank">Mapbox</a> per visualizzare mappe stupende, recuperare i dati altimetrici e consentire la ricerca di luoghi.
Sfortunatamente, questo è costoso. Sfortunatamente, fare tutto ciò è costoso.
Se ti piace utilizzare questo strumento e lo trovi utile, per favore considera di fare una piccola donazione per aiutare a mantenere il sito web gratuito e senza pubblicità. Se ti piace utilizzare questo strumento e lo trovi utile, per favore considera di fare una piccola donazione per aiutare a mantenere il sito web gratuito e senza pubblicità.
Grazie mille per il vostro supporto! ❤️ Grazie mille per il vostro supporto! ❤️

View File

@@ -2,7 +2,7 @@
import { HeartHandshake } from '@lucide/svelte'; import { HeartHandshake } from '@lucide/svelte';
</script> </script>
## <HeartHandshake size="18" class="inline-block align-baseline" /> Help keep the website free (and ad-free) ## <HeartHandshake size="18" class="inline-block align-baseline" /> Hãy giúp duy trì trang web miễn phí (và không có quảng cáo)
Khi bạn thêm hoặc di chuyển các điểm định vị, máy chủ của chúng tôi sẽ tính toán đoạn đường tốt nhất trên mạng lưới giao thông. Khi bạn thêm hoặc di chuyển các điểm định vị, máy chủ của chúng tôi sẽ tính toán đoạn đường tốt nhất trên mạng lưới giao thông.
Chúng tôi cũng sử dụng các API từ <a href="https://mapbox.com" target="_blank">Mapbox</a> để hiển thị đa dạng các bản đồ, lưu trữ các dữ liệu độ cao cũng như giúp bạn có thể tìm kiếm các địa điểm khác nhau. Chúng tôi cũng sử dụng các API từ <a href="https://mapbox.com" target="_blank">Mapbox</a> để hiển thị đa dạng các bản đồ, lưu trữ các dữ liệu độ cao cũng như giúp bạn có thể tìm kiếm các địa điểm khác nhau.

View File

@@ -1,5 +1,5 @@
Mapbox is the company that provides some of the beautiful maps on this website. Mapbox là công ty cung cấp một số bản đồ đẹp trên trang web này.
They also develop the <a href="https://github.com/mapbox/mapbox-gl-js" target="_blank">map engine</a> which powers **gpx.studio**. Họ cũng phát triển <a href="https://github.com/mapbox/mapbox-gl-js" target="_blank">công cụ bản đồ</a> cung cấp sức mạnh cho **gpx.studio**.
We are incredibly fortunate and grateful to be part of their <a href="https://mapbox.com/community" target="_blank">Community</a> program, which supports nonprofits, educational institutions, and positive impact organizations. Chúng tôi vô cùng may mắn và biết ơn khi được tham gia chương trình <a href="https://mapbox.com/community" target="_blank">Cộng đồng</a> của họ, chương trình hỗ trợ các tổ chức phi lợi nhuận, các tổ chức giáo dục và các tổ chức tạo ra tác động tích cực.
This partnership allows **gpx.studio** to benefit from Mapbox tools at discounted prices, greatly contributing to the financial viability of the project and enabling us to offer the best possible user experience. Sự hợp tác này cho phép **gpx.studio** được hưởng lợi từ các công cụ của Mapbox với giá ưu đãi, góp phần đáng kể vào tính khả thi về tài chính của dự án và giúp chúng tôi mang đến trải nghiệm người dùng tốt nhất có thể.

View File

@@ -9,8 +9,8 @@ title: Edit actions
# { title } # { title }
Unlike the file actions, the edit actions can potentially modify the content of the currently selected files. Không giống như các thao tác trên tệp, các thao tác chỉnh sửa có thể thay đổi nội dung của các tệp hiện đang được chọn.
Moreover, when the tree layout of the files list is enabled (see [Files and statistics](../files-and-stats)), they can also be applied to [tracks, segments, and points of interest](../gpx). Hơn nữa, khi bố cục dạng cây của danh sách tệp được bật (xem [Tệp và thống kê](../files-and-stats)), chúng cũng có thể được áp dụng cho [đường đi, đoạn đường và điểm quan tâm](../gpx).
Therefore, we will refer to the elements that can be modified by these actions as _file items_. Therefore, we will refer to the elements that can be modified by these actions as _file items_.
Note that except for the undo and redo actions, the edit actions are also accessible through the context menu (right-click) of the file items. Note that except for the undo and redo actions, the edit actions are also accessible through the context menu (right-click) of the file items.

View File

@@ -31,7 +31,7 @@ Create a copy of the currently selected files.
### <FileX size="16" class="inline-block" style="margin-bottom: 2px" /> Delete ### <FileX size="16" class="inline-block" style="margin-bottom: 2px" /> Delete
Delete the currently selected files. .
### <FileX size="16" class="inline-block" style="margin-bottom: 2px" /> Delete all ### <FileX size="16" class="inline-block" style="margin-bottom: 2px" /> Delete all

View File

@@ -29,9 +29,9 @@ title: 文件
创建当前选中文件的副本。 创建当前选中文件的副本。
### <FileX size="16" class="inline-block" style="margin-bottom: 2px" /> Delete ### <FileX size="16" class="inline-block" style="margin-bottom: 2px" /> 删除
Delete the currently selected files. 删除当前选中的文件。
### <FileX size="16" class="inline-block" style="margin-bottom: 2px" /> 删除全部 ### <FileX size="16" class="inline-block" style="margin-bottom: 2px" /> 删除全部

View File

@@ -1,6 +1,6 @@
import { get } from 'svelte/store'; import { get } from 'svelte/store';
import { selection } from '$lib/logic/selection'; import { selection } from '$lib/logic/selection';
import mapboxgl from 'mapbox-gl'; import maplibregl from 'maplibre-gl';
import { ListFileItem, ListWaypointItem } from '$lib/components/file-list/file-list'; import { ListFileItem, ListWaypointItem } from '$lib/components/file-list/file-list';
import { fileStateCollection, GPXFileStateCollectionObserver } from '$lib/logic/file-state'; import { fileStateCollection, GPXFileStateCollectionObserver } from '$lib/logic/file-state';
import { gpxStatistics } from '$lib/logic/statistics'; import { gpxStatistics } from '$lib/logic/statistics';
@@ -10,7 +10,7 @@ import type { Coordinates } from 'gpx';
import { page } from '$app/state'; import { page } from '$app/state';
export class BoundsManager { export class BoundsManager {
private _bounds: mapboxgl.LngLatBounds = new mapboxgl.LngLatBounds(); private _bounds: maplibregl.LngLatBounds = new maplibregl.LngLatBounds();
private _files: Set<string> = new Set(); private _files: Set<string> = new Set();
private _fileStateCollectionObserver: GPXFileStateCollectionObserver | null = null; private _fileStateCollectionObserver: GPXFileStateCollectionObserver | null = null;
private _unsubscribes: (() => void)[] = []; private _unsubscribes: (() => void)[] = [];
@@ -87,12 +87,12 @@ export class BoundsManager {
} }
this._unsubscribes.forEach((unsubscribe) => unsubscribe()); this._unsubscribes.forEach((unsubscribe) => unsubscribe());
this._unsubscribes = []; this._unsubscribes = [];
this._bounds = new mapboxgl.LngLatBounds([180, 90, -180, -90]); this._bounds = new maplibregl.LngLatBounds([180, 90, -180, -90]);
} }
centerMapOnSelection() { centerMapOnSelection() {
let selected = get(selection).getSelected(); let selected = get(selection).getSelected();
let bounds = new mapboxgl.LngLatBounds(); let bounds = new maplibregl.LngLatBounds();
if (selected.find((item) => item instanceof ListWaypointItem)) { if (selected.find((item) => item instanceof ListWaypointItem)) {
selection.applyToOrderedSelectedItemsFromFile((fileId, level, items) => { selection.applyToOrderedSelectedItemsFromFile((fileId, level, items) => {

View File

@@ -215,7 +215,7 @@ export const fileActions = {
reverseSelection: () => { reverseSelection: () => {
if ( if (
!get(selection).hasAnyChildren(new ListRootItem(), true, ['waypoints']) || !get(selection).hasAnyChildren(new ListRootItem(), true, ['waypoints']) ||
get(gpxStatistics).local.points?.length <= 1 get(gpxStatistics).global.length <= 1
) { ) {
return; return;
} }
@@ -345,19 +345,20 @@ export const fileActions = {
let startTime: Date | undefined = undefined; let startTime: Date | undefined = undefined;
if (speed !== undefined) { if (speed !== undefined) {
if ( if (
statistics.local.points.length > 0 && statistics.global.length > 0 &&
statistics.local.points[0].time !== undefined statistics.getTrackPoint(0)!.trkpt.time !== undefined
) { ) {
startTime = statistics.local.points[0].time; startTime = statistics.getTrackPoint(0)!.trkpt.time;
} else { } else {
let index = statistics.local.points.findIndex( for (let i = 0; i < statistics.global.length; i++) {
(point) => point.time !== undefined const point = statistics.getTrackPoint(i)!;
); if (point.trkpt.time !== undefined) {
if (index !== -1 && statistics.local.points[index].time) { startTime = new Date(
startTime = new Date( point.trkpt.time.getTime() -
statistics.local.points[index].time.getTime() - (1000 * 3600 * point.distance.total) / speed
(1000 * 3600 * statistics.local.distance.total[index]) / speed );
); break;
}
} }
} }
} }
@@ -806,7 +807,7 @@ export const fileActions = {
}); });
}); });
}, },
addElevationToSelection: async (map: mapboxgl.Map) => { addElevationToSelection: async () => {
if (get(selection).size === 0) { if (get(selection).size === 0) {
return; return;
} }

View File

@@ -1,6 +1,7 @@
import { type Database } from '$lib/db'; import { type Database } from '$lib/db';
import { liveQuery } from 'dexie'; import { liveQuery } from 'dexie';
import { import {
basemaps,
defaultBasemap, defaultBasemap,
defaultBasemapTree, defaultBasemapTree,
defaultOpacities, defaultOpacities,
@@ -8,7 +9,11 @@ import {
defaultOverlayTree, defaultOverlayTree,
defaultOverpassQueries, defaultOverpassQueries,
defaultOverpassTree, defaultOverpassTree,
defaultTerrainSource,
overlays,
overpassQueryData,
type CustomLayer, type CustomLayer,
type LayerTreeType,
} from '$lib/assets/layers'; } from '$lib/assets/layers';
import { browser } from '$app/environment'; import { browser } from '$app/environment';
import { get, writable, type Writable } from 'svelte/store'; import { get, writable, type Writable } from 'svelte/store';
@@ -18,10 +23,12 @@ export class Setting<V> {
private _subscription: { unsubscribe: () => void } | null = null; private _subscription: { unsubscribe: () => void } | null = null;
private _key: string; private _key: string;
private _value: Writable<V>; private _value: Writable<V>;
private _validator?: (value: V) => V;
constructor(key: string, initial: V) { constructor(key: string, initial: V, validator?: (value: V) => V) {
this._key = key; this._key = key;
this._value = writable(initial); this._value = writable(initial);
this._validator = validator;
} }
connectToDatabase(db: Database) { connectToDatabase(db: Database) {
@@ -35,6 +42,9 @@ export class Setting<V> {
this._value.set(value); this._value.set(value);
} }
} else { } else {
if (this._validator) {
value = this._validator(value);
}
this._value.set(value); this._value.set(value);
} }
first = false; first = false;
@@ -72,11 +82,13 @@ export class SettingInitOnFirstRead<V> {
private _key: string; private _key: string;
private _value: Writable<V | undefined>; private _value: Writable<V | undefined>;
private _initial: V; private _initial: V;
private _validator?: (value: V) => V;
constructor(key: string, initial: V) { constructor(key: string, initial: V, validator?: (value: V) => V) {
this._key = key; this._key = key;
this._value = writable(undefined); this._value = writable(undefined);
this._initial = initial; this._initial = initial;
this._validator = validator;
} }
connectToDatabase(db: Database) { connectToDatabase(db: Database) {
@@ -92,6 +104,9 @@ export class SettingInitOnFirstRead<V> {
this._value.set(value); this._value.set(value);
} }
} else { } else {
if (this._validator) {
value = this._validator(value);
}
this._value.set(value); this._value.set(value);
} }
first = false; first = false;
@@ -127,36 +142,166 @@ export class SettingInitOnFirstRead<V> {
} }
} }
function getValueValidator<V>(allowed: V[], fallback: V) {
const dict = new Set<V>(allowed);
return (value: V) => (dict.has(value) ? value : fallback);
}
function getArrayValidator<V>(allowed: V[]) {
const dict = new Set<V>(allowed);
return (value: V[]) => value.filter((v) => dict.has(v));
}
function getLayerValidator(allowed: Record<string, any>, fallback: string) {
return (layer: string) =>
allowed.hasOwnProperty(layer) ||
layer.startsWith('custom-') ||
layer.startsWith('extension-')
? layer
: fallback;
}
function filterLayerTree(t: LayerTreeType, allowed: Record<string, any>): LayerTreeType {
const filtered: LayerTreeType = {};
Object.entries(t).forEach(([key, value]) => {
if (typeof value === 'object') {
filtered[key] = filterLayerTree(value, allowed);
} else if (
allowed.hasOwnProperty(key) ||
key.startsWith('custom-') ||
key.startsWith('extension-')
) {
filtered[key] = value;
}
});
return filtered;
}
function getLayerTreeValidator(allowed: Record<string, any>) {
return (value: LayerTreeType) => filterLayerTree(value, allowed);
}
type DistanceUnits = 'metric' | 'imperial' | 'nautical';
type VelocityUnits = 'speed' | 'pace';
type TemperatureUnits = 'celsius' | 'fahrenheit';
type AdditionalDataset = 'speed' | 'hr' | 'cad' | 'atemp' | 'power';
type ElevationFill = 'slope' | 'surface' | undefined;
type RoutingProfile =
| 'bike'
| 'racing_bike'
| 'gravel_bike'
| 'mountain_bike'
| 'foot'
| 'motorcycle'
| 'water'
| 'railway';
type TerrainSource = 'maptiler-dem' | 'mapterhorn';
type StreetViewSource = 'mapillary' | 'google';
export const settings = { export const settings = {
distanceUnits: new Setting<'metric' | 'imperial' | 'nautical'>('distanceUnits', 'metric'), distanceUnits: new Setting<DistanceUnits>(
velocityUnits: new Setting<'speed' | 'pace'>('velocityUnits', 'speed'), 'distanceUnits',
temperatureUnits: new Setting<'celsius' | 'fahrenheit'>('temperatureUnits', 'celsius'), 'metric',
getValueValidator<DistanceUnits>(['metric', 'imperial', 'nautical'], 'metric')
),
velocityUnits: new Setting<VelocityUnits>(
'velocityUnits',
'speed',
getValueValidator<VelocityUnits>(['speed', 'pace'], 'speed')
),
temperatureUnits: new Setting<TemperatureUnits>(
'temperatureUnits',
'celsius',
getValueValidator<TemperatureUnits>(['celsius', 'fahrenheit'], 'celsius')
),
elevationProfile: new Setting<boolean>('elevationProfile', true), elevationProfile: new Setting<boolean>('elevationProfile', true),
additionalDatasets: new Setting<string[]>('additionalDatasets', []), additionalDatasets: new Setting<AdditionalDataset[]>(
elevationFill: new Setting<'slope' | 'surface' | undefined>('elevationFill', undefined), 'additionalDatasets',
[],
getArrayValidator<AdditionalDataset>(['speed', 'hr', 'cad', 'atemp', 'power'])
),
elevationFill: new Setting<ElevationFill>(
'elevationFill',
undefined,
getValueValidator(['slope', 'surface', undefined], undefined)
),
treeFileView: new Setting<boolean>('fileView', false), treeFileView: new Setting<boolean>('fileView', false),
minimizeRoutingMenu: new Setting('minimizeRoutingMenu', false), minimizeRoutingMenu: new Setting('minimizeRoutingMenu', false),
routing: new Setting('routing', true), routing: new Setting('routing', true),
routingProfile: new Setting('routingProfile', 'bike'), routingProfile: new Setting<RoutingProfile>(
'routingProfile',
'bike',
getValueValidator<RoutingProfile>(
[
'bike',
'racing_bike',
'gravel_bike',
'mountain_bike',
'foot',
'motorcycle',
'water',
'railway',
],
'bike'
)
),
privateRoads: new Setting('privateRoads', false), privateRoads: new Setting('privateRoads', false),
currentBasemap: new Setting('currentBasemap', defaultBasemap), currentBasemap: new Setting(
previousBasemap: new Setting('previousBasemap', defaultBasemap), 'currentBasemap',
selectedBasemapTree: new Setting('selectedBasemapTree', defaultBasemapTree), defaultBasemap,
currentOverlays: new SettingInitOnFirstRead('currentOverlays', defaultOverlays), getLayerValidator(basemaps, defaultBasemap)
previousOverlays: new Setting('previousOverlays', defaultOverlays), ),
selectedOverlayTree: new Setting('selectedOverlayTree', defaultOverlayTree), previousBasemap: new Setting(
'previousBasemap',
defaultBasemap,
getLayerValidator(Object.keys(basemaps), defaultBasemap)
),
selectedBasemapTree: new Setting(
'selectedBasemapTree',
defaultBasemapTree,
getLayerTreeValidator(basemaps)
),
currentOverlays: new SettingInitOnFirstRead(
'currentOverlays',
defaultOverlays,
getLayerTreeValidator(overlays)
),
previousOverlays: new Setting(
'previousOverlays',
defaultOverlays,
getLayerTreeValidator(overlays)
),
selectedOverlayTree: new Setting(
'selectedOverlayTree',
defaultOverlayTree,
getLayerTreeValidator(overlays)
),
currentOverpassQueries: new SettingInitOnFirstRead( currentOverpassQueries: new SettingInitOnFirstRead(
'currentOverpassQueries', 'currentOverpassQueries',
defaultOverpassQueries defaultOverpassQueries,
getLayerTreeValidator(overpassQueryData)
),
selectedOverpassTree: new Setting(
'selectedOverpassTree',
defaultOverpassTree,
getLayerTreeValidator(overpassQueryData)
), ),
selectedOverpassTree: new Setting('selectedOverpassTree', defaultOverpassTree),
opacities: new Setting('opacities', defaultOpacities), opacities: new Setting('opacities', defaultOpacities),
customLayers: new Setting<Record<string, CustomLayer>>('customLayers', {}), customLayers: new Setting<Record<string, CustomLayer>>('customLayers', {}),
customBasemapOrder: new Setting<string[]>('customBasemapOrder', []), customBasemapOrder: new Setting<string[]>('customBasemapOrder', []),
customOverlayOrder: new Setting<string[]>('customOverlayOrder', []), customOverlayOrder: new Setting<string[]>('customOverlayOrder', []),
terrainSource: new Setting<TerrainSource>(
'terrainSource',
defaultTerrainSource,
getValueValidator(['maptiler-dem', 'mapterhorn'], defaultTerrainSource)
),
directionMarkers: new Setting('directionMarkers', false), directionMarkers: new Setting('directionMarkers', false),
distanceMarkers: new Setting('distanceMarkers', false), distanceMarkers: new Setting('distanceMarkers', false),
streetViewSource: new Setting('streetViewSource', 'mapillary'), streetViewSource: new Setting<StreetViewSource>(
'streetViewSource',
'mapillary',
getValueValidator<StreetViewSource>(['mapillary', 'google'], 'mapillary')
),
fileOrder: new Setting<string[]>('fileOrder', []), fileOrder: new Setting<string[]>('fileOrder', []),
defaultOpacity: new Setting('defaultOpacity', 0.7), defaultOpacity: new Setting('defaultOpacity', 0.7),
defaultWidth: new Setting('defaultWidth', browser && window.innerWidth < 600 ? 8 : 5), defaultWidth: new Setting('defaultWidth', browser && window.innerWidth < 600 ? 8 : 5),

View File

@@ -1,18 +1,24 @@
import { ListItem, ListLevel } from '$lib/components/file-list/file-list'; import { ListItem, ListLevel } from '$lib/components/file-list/file-list';
import { GPXFile, GPXStatistics, type Track } from 'gpx'; import { GPXFile, GPXStatistics, GPXStatisticsGroup, type Track } from 'gpx';
import maplibregl from 'maplibre-gl';
export class GPXStatisticsTree { export class GPXStatisticsTree {
level: ListLevel; level: ListLevel;
statistics: { statistics: {
[key: string]: GPXStatisticsTree | GPXStatistics; [key: string]: GPXStatisticsTree | GPXStatistics;
} = {}; } = {};
wptBounds: maplibregl.LngLatBounds;
constructor(element: GPXFile | Track) { constructor(element: GPXFile | Track) {
this.wptBounds = new maplibregl.LngLatBounds();
if (element instanceof GPXFile) { if (element instanceof GPXFile) {
this.level = ListLevel.FILE; this.level = ListLevel.FILE;
element.children.forEach((child, index) => { element.children.forEach((child, index) => {
this.statistics[index] = new GPXStatisticsTree(child); this.statistics[index] = new GPXStatisticsTree(child);
}); });
element.wpt.forEach((wpt) => {
this.wptBounds.extend(wpt.getCoordinates());
});
} else { } else {
this.level = ListLevel.TRACK; this.level = ListLevel.TRACK;
element.children.forEach((child, index) => { element.children.forEach((child, index) => {
@@ -21,35 +27,48 @@ export class GPXStatisticsTree {
} }
} }
getStatisticsFor(item: ListItem): GPXStatistics { getStatisticsFor(item: ListItem): GPXStatisticsGroup {
let statistics = []; let statistics = new GPXStatisticsGroup();
let id = item.getIdAtLevel(this.level); let id = item.getIdAtLevel(this.level);
if (id === undefined || id === 'waypoints') { if (id === undefined || id === 'waypoints') {
Object.keys(this.statistics).forEach((key) => { Object.keys(this.statistics).forEach((key) => {
if (this.statistics[key] instanceof GPXStatistics) { if (this.statistics[key] instanceof GPXStatistics) {
statistics.push(this.statistics[key]); statistics.add(this.statistics[key]);
} else { } else {
statistics.push(this.statistics[key].getStatisticsFor(item)); statistics.add(this.statistics[key].getStatisticsFor(item));
} }
}); });
} else { } else {
let child = this.statistics[id]; let child = this.statistics[id];
if (child instanceof GPXStatistics) { if (child instanceof GPXStatistics) {
statistics.push(child); statistics.add(child);
} else if (child !== undefined) { } else if (child !== undefined) {
statistics.push(child.getStatisticsFor(item)); statistics.add(child.getStatisticsFor(item));
} }
} }
if (statistics.length === 0) { return statistics;
return new GPXStatistics(); }
} else if (statistics.length === 1) {
return statistics[0]; intersectsBBox(bounds: maplibregl.LngLatBounds): boolean {
} else { for (let key in this.statistics) {
return statistics.reduce((acc, curr) => { const stats = this.statistics[key];
acc.mergeWith(curr); if (stats instanceof GPXStatistics) {
return acc; const bbox = new maplibregl.LngLatBounds(
}, new GPXStatistics()); stats.global.bounds.southWest,
stats.global.bounds.northEast
);
if (!bbox.isEmpty() && bbox.intersects(bounds)) {
return true;
}
} else if (stats.intersectsBBox(bounds)) {
return true;
}
} }
return false;
}
intersectsWaypointBBox(bounds: maplibregl.LngLatBounds): boolean {
return !this.wptBounds.isEmpty() && this.wptBounds.intersects(bounds);
} }
} }
export type GPXFileWithStatistics = { file: GPXFile; statistics: GPXStatisticsTree }; export type GPXFileWithStatistics = { file: GPXFile; statistics: GPXStatisticsTree };

View File

@@ -1,5 +1,5 @@
import { selection } from '$lib/logic/selection'; import { selection } from '$lib/logic/selection';
import { GPXStatistics } from 'gpx'; import { GPXGlobalStatistics, GPXStatisticsGroup, type Coordinates } from 'gpx';
import { fileStateCollection, GPXFileState } from '$lib/logic/file-state'; import { fileStateCollection, GPXFileState } from '$lib/logic/file-state';
import { import {
ListFileItem, ListFileItem,
@@ -12,7 +12,7 @@ import { settings } from '$lib/logic/settings';
const { fileOrder } = settings; const { fileOrder } = settings;
export class SelectedGPXStatistics { export class SelectedGPXStatistics {
private _statistics: Writable<GPXStatistics>; private _statistics: Writable<GPXStatisticsGroup>;
private _files: Map< private _files: Map<
string, string,
{ {
@@ -22,18 +22,21 @@ export class SelectedGPXStatistics {
>; >;
constructor() { constructor() {
this._statistics = writable(new GPXStatistics()); this._statistics = writable(new GPXStatisticsGroup());
this._files = new Map(); this._files = new Map();
selection.subscribe(() => this.update()); selection.subscribe(() => this.update());
fileOrder.subscribe(() => this.update()); fileOrder.subscribe(() => this.update());
} }
subscribe(run: (value: GPXStatistics) => void, invalidate?: (value?: GPXStatistics) => void) { subscribe(
run: (value: GPXStatisticsGroup) => void,
invalidate?: (value?: GPXStatisticsGroup) => void
) {
return this._statistics.subscribe(run, invalidate); return this._statistics.subscribe(run, invalidate);
} }
update() { update() {
let statistics = new GPXStatistics(); let statistics = new GPXStatisticsGroup();
selection.applyToOrderedSelectedItemsFromFile((fileId, level, items) => { selection.applyToOrderedSelectedItemsFromFile((fileId, level, items) => {
let stats = fileStateCollection.getStatistics(fileId); let stats = fileStateCollection.getStatistics(fileId);
if (stats) { if (stats) {
@@ -43,7 +46,7 @@ export class SelectedGPXStatistics {
!(item instanceof ListWaypointItem || item instanceof ListWaypointsItem) || !(item instanceof ListWaypointItem || item instanceof ListWaypointsItem) ||
first first
) { ) {
statistics.mergeWith(stats.getStatisticsFor(item)); statistics.add(stats.getStatisticsFor(item));
first = false; first = false;
} }
}); });
@@ -76,9 +79,11 @@ export class SelectedGPXStatistics {
export const gpxStatistics = new SelectedGPXStatistics(); export const gpxStatistics = new SelectedGPXStatistics();
export const slicedGPXStatistics: Writable<[GPXStatistics, number, number] | undefined> = export const slicedGPXStatistics: Writable<[GPXGlobalStatistics, number, number] | undefined> =
writable(undefined); writable(undefined);
export const hoveredPoint: Writable<Coordinates | null> = writable(null);
gpxStatistics.subscribe(() => { gpxStatistics.subscribe(() => {
slicedGPXStatistics.set(undefined); slicedGPXStatistics.set(undefined);
}); });

View File

@@ -229,6 +229,9 @@ export function getConvertedVelocity(
} }
} }
export function getConvertedTemperature(value: number) { export function getConvertedTemperature(
return get(temperatureUnits) === 'celsius' ? value : celsiusToFahrenheit(value); value: number,
targetTemperatureUnits = get(temperatureUnits)
) {
return targetTemperatureUnits === 'celsius' ? value : celsiusToFahrenheit(value);
} }

View File

@@ -3,12 +3,11 @@ import { twMerge } from 'tailwind-merge';
import { base } from '$app/paths'; import { base } from '$app/paths';
import { languages } from '$lib/languages'; import { languages } from '$lib/languages';
import { TrackPoint, Waypoint, type Coordinates, crossarcDistance, distance, GPXFile } from 'gpx'; import { TrackPoint, Waypoint, type Coordinates, crossarcDistance, distance, GPXFile } from 'gpx';
import mapboxgl from 'mapbox-gl'; import maplibregl from 'maplibre-gl';
import { pointToTile, pointToTileFraction } from '@mapbox/tilebelt'; import { pointToTile, pointToTileFraction } from '@mapbox/tilebelt';
import { PUBLIC_MAPBOX_TOKEN } from '$env/static/public';
import PNGReader from 'png.js';
import type { GPXStatisticsTree } from '$lib/logic/statistics-tree'; import type { GPXStatisticsTree } from '$lib/logic/statistics-tree';
import { ListTrackSegmentItem } from '$lib/components/file-list/file-list'; import { ListTrackSegmentItem } from '$lib/components/file-list/file-list';
import { PUBLIC_MAPTILER_KEY } from '$env/static/public';
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)); return twMerge(clsx(inputs));
@@ -62,7 +61,7 @@ export function getClosestTrackSegments(
let segmentBounds = segmentStatistics.global.bounds; let segmentBounds = segmentStatistics.global.bounds;
let northEast = segmentBounds.northEast; let northEast = segmentBounds.northEast;
let southWest = segmentBounds.southWest; let southWest = segmentBounds.southWest;
let bounds = new mapboxgl.LngLatBounds(southWest, northEast); let bounds = new maplibregl.LngLatBounds(southWest, northEast);
if (bounds.contains(point)) { if (bounds.contains(point)) {
segmentBoundsDistances.push([0, trackIndex, segmentIndex]); segmentBoundsDistances.push([0, trackIndex, segmentIndex]);
} else { } else {
@@ -110,33 +109,49 @@ export function getElevation(
let coordinates = points.map((point) => let coordinates = points.map((point) =>
point instanceof TrackPoint || point instanceof Waypoint ? point.getCoordinates() : point point instanceof TrackPoint || point instanceof Waypoint ? point.getCoordinates() : point
); );
let bbox = new mapboxgl.LngLatBounds(); let bbox = new maplibregl.LngLatBounds();
coordinates.forEach((coord) => bbox.extend(coord)); coordinates.forEach((coord) => bbox.extend(coord));
let tiles = coordinates.map((coord) => pointToTile(coord.lon, coord.lat, ELEVATION_ZOOM)); let tiles = coordinates.map((coord) => pointToTile(coord.lon, coord.lat, ELEVATION_ZOOM));
let uniqueTiles = Array.from(new Set(tiles.map((tile) => tile.join(',')))).map((tile) => let uniqueTiles = Array.from(new Set(tiles.map((tile) => tile.join(',')))).map((tile) =>
tile.split(',').map((x) => parseInt(x)) tile.split(',').map((x) => parseInt(x))
); );
let pngs = new Map<string, any>(); let images = new Map<string, ImageData>();
const getPixelFromImageData = (imageData: ImageData, x: number, y: number): number[] => {
const index = (y * imageData.width + x) * 4;
return [imageData.data[index], imageData.data[index + 1], imageData.data[index + 2]];
};
let promises = uniqueTiles.map((tile) => let promises = uniqueTiles.map((tile) =>
fetch( fetch(
`https://api.mapbox.com/v4/mapbox.mapbox-terrain-dem-v1/${ELEVATION_ZOOM}/${tile[0]}/${tile[1]}@2x.pngraw?access_token=${PUBLIC_MAPBOX_TOKEN}`, `https://api.maptiler.com/tiles/terrain-rgb-v2/${ELEVATION_ZOOM}/${tile[0]}/${tile[1]}.webp?key=${PUBLIC_MAPTILER_KEY}`,
{ cache: 'force-cache' } { cache: 'force-cache' }
) )
.then((response) => response.arrayBuffer()) .then((response) => response.blob())
.then( .then(
(buffer) => (blob) =>
new Promise((resolve) => { new Promise<void>((resolve) => {
let png = new PNGReader(new Uint8Array(buffer)); const url = URL.createObjectURL(blob);
png.parse((err, png) => { const img = new Image();
if (err) { img.onload = () => {
resolve(false); // Also resolve so that Promise.all doesn't fail const canvas = document.createElement('canvas');
} else { canvas.width = img.width;
pngs.set(tile.join(','), png); canvas.height = img.height;
resolve(true); const ctx = canvas.getContext('2d');
if (ctx) {
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, img.width, img.height);
images.set(tile.join(','), imageData);
} }
}); URL.revokeObjectURL(url);
resolve();
};
img.onerror = () => {
URL.revokeObjectURL(url);
resolve();
};
img.src = url;
}) })
) )
); );
@@ -144,9 +159,9 @@ export function getElevation(
return Promise.all(promises).then(() => return Promise.all(promises).then(() =>
coordinates.map((coord, index) => { coordinates.map((coord, index) => {
let tile = tiles[index]; let tile = tiles[index];
let png = pngs.get(tile.join(',')); let imageData = images.get(tile.join(','));
if (!png) { if (!imageData) {
return 0; return 0;
} }
@@ -158,10 +173,11 @@ export function getElevation(
let dx = x - _x; let dx = x - _x;
let dy = y - _y; let dy = y - _y;
const p00 = png.getPixel(_x, _y); const p00 = getPixelFromImageData(imageData, _x, _y);
const p01 = png.getPixel(_x, _y + (_y + 1 == tileSize ? 0 : 1)); const p01 = getPixelFromImageData(imageData, _x, _y + (_y + 1 == tileSize ? 0 : 1));
const p10 = png.getPixel(_x + (_x + 1 == tileSize ? 0 : 1), _y); const p10 = getPixelFromImageData(imageData, _x + (_x + 1 == tileSize ? 0 : 1), _y);
const p11 = png.getPixel( const p11 = getPixelFromImageData(
imageData,
_x + (_x + 1 == tileSize ? 0 : 1), _x + (_x + 1 == tileSize ? 0 : 1),
_y + (_y + 1 == tileSize ? 0 : 1) _y + (_y + 1 == tileSize ? 0 : 1)
); );
@@ -181,6 +197,18 @@ export function getElevation(
); );
} }
export function loadSVGIcon(map: maplibregl.Map, id: string, svg: string) {
if (!map.hasImage(id)) {
let icon = new Image(100, 100);
icon.onload = () => {
if (!map.hasImage(id)) {
map.addImage(id, icon);
}
};
icon.src = 'data:image/svg+xml,' + encodeURIComponent(svg);
}
}
export function isMac() { export function isMac() {
return navigator.userAgent.toUpperCase().indexOf('MAC') >= 0; return navigator.userAgent.toUpperCase().indexOf('MAC') >= 0;
} }

View File

@@ -282,6 +282,7 @@
"update": "Update layer" "update": "Update layer"
}, },
"opacity": "Overlay opacity", "opacity": "Overlay opacity",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "Basemaps", "basemaps": "Basemaps",
"overlays": "Overlays", "overlays": "Overlays",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Slope", "swisstopoSlope": "swisstopo Slope",
"swisstopoHiking": "swisstopo Hiking", "swisstopoHiking": "swisstopo Hiking",
"swisstopoHikingClosures": "swisstopo Hiking Closures", "swisstopoHikingClosures": "swisstopo Hiking Closures",
@@ -377,7 +380,9 @@
"railway-station": "Railway Station", "railway-station": "Railway Station",
"tram-stop": "Tram Stop", "tram-stop": "Tram Stop",
"bus-stop": "Bus Stop", "bus-stop": "Bus Stop",
"ferry": "Ferry" "ferry": "Ferry",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {

View File

@@ -282,6 +282,7 @@
"update": "Actualitza la capa" "update": "Actualitza la capa"
}, },
"opacity": "Opacitat de la superposició", "opacity": "Opacitat de la superposició",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "Mapes base", "basemaps": "Mapes base",
"overlays": "Capes", "overlays": "Capes",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Slope", "swisstopoSlope": "swisstopo Slope",
"swisstopoHiking": "swisstopo Hiking", "swisstopoHiking": "swisstopo Hiking",
"swisstopoHikingClosures": "swisstopo Hiking Closures", "swisstopoHikingClosures": "swisstopo Hiking Closures",
@@ -377,7 +380,9 @@
"railway-station": "Estació de tren", "railway-station": "Estació de tren",
"tram-stop": "Parada de tramvia", "tram-stop": "Parada de tramvia",
"bus-stop": "Parada d'autobús", "bus-stop": "Parada d'autobús",
"ferry": "Ferri" "ferry": "Ferri",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {

View File

@@ -282,6 +282,7 @@
"update": "Aktualizovat vrstvu" "update": "Aktualizovat vrstvu"
}, },
"opacity": "Průhlednost překryvu", "opacity": "Průhlednost překryvu",
"terrain": "Zdroj terénu",
"label": { "label": {
"basemaps": "Základní mapy", "basemaps": "Základní mapy",
"overlays": "Překrytí", "overlays": "Překrytí",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Vrstevnice", "swisstopoSlope": "swisstopo Vrstevnice",
"swisstopoHiking": "swisstopo Turistická", "swisstopoHiking": "swisstopo Turistická",
"swisstopoHikingClosures": "swisstopo Turistické uzávěry", "swisstopoHikingClosures": "swisstopo Turistické uzávěry",
@@ -377,7 +380,9 @@
"railway-station": "Železniční stanice", "railway-station": "Železniční stanice",
"tram-stop": "Zastávka tramvaje", "tram-stop": "Zastávka tramvaje",
"bus-stop": "Autobusová zastávka", "bus-stop": "Autobusová zastávka",
"ferry": "Trajekt" "ferry": "Trajekt",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {

View File

@@ -282,6 +282,7 @@
"update": "Update layer" "update": "Update layer"
}, },
"opacity": "Overlay opacity", "opacity": "Overlay opacity",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "Basemaps", "basemaps": "Basemaps",
"overlays": "Overlays", "overlays": "Overlays",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Slope", "swisstopoSlope": "swisstopo Slope",
"swisstopoHiking": "swisstopo Hiking", "swisstopoHiking": "swisstopo Hiking",
"swisstopoHikingClosures": "swisstopo Hiking Closures", "swisstopoHikingClosures": "swisstopo Hiking Closures",
@@ -377,7 +380,9 @@
"railway-station": "Railway Station", "railway-station": "Railway Station",
"tram-stop": "Tram Stop", "tram-stop": "Tram Stop",
"bus-stop": "Bus Stop", "bus-stop": "Bus Stop",
"ferry": "Ferry" "ferry": "Ferry",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {

View File

@@ -282,6 +282,7 @@
"update": "Layer aktualisieren" "update": "Layer aktualisieren"
}, },
"opacity": "Deckkraft der Überlagerung", "opacity": "Deckkraft der Überlagerung",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "Basiskarte", "basemaps": "Basiskarte",
"overlays": "Ebenen", "overlays": "Ebenen",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Neigung", "swisstopoSlope": "swisstopo Neigung",
"swisstopoHiking": "swisstopo Wandern", "swisstopoHiking": "swisstopo Wandern",
"swisstopoHikingClosures": "swisstopo Wanderungen Schließungen", "swisstopoHikingClosures": "swisstopo Wanderungen Schließungen",
@@ -377,7 +380,9 @@
"railway-station": "Bahnhof", "railway-station": "Bahnhof",
"tram-stop": "Straßenbahnhaltestelle", "tram-stop": "Straßenbahnhaltestelle",
"bus-stop": "Bushaltestelle", "bus-stop": "Bushaltestelle",
"ferry": "Fähre" "ferry": "Fähre",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {
@@ -473,7 +478,7 @@
}, },
"homepage": { "homepage": {
"website": "Webseite", "website": "Webseite",
"home": "Zuhause", "home": "Startseite",
"app": "App", "app": "App",
"contact": "Kontakt", "contact": "Kontakt",
"reddit": "Reddit", "reddit": "Reddit",

View File

@@ -282,6 +282,7 @@
"update": "Update layer" "update": "Update layer"
}, },
"opacity": "Overlay opacity", "opacity": "Overlay opacity",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "Basemaps", "basemaps": "Basemaps",
"overlays": "Overlays", "overlays": "Overlays",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Slope", "swisstopoSlope": "swisstopo Slope",
"swisstopoHiking": "swisstopo Hiking", "swisstopoHiking": "swisstopo Hiking",
"swisstopoHikingClosures": "swisstopo Hiking Closures", "swisstopoHikingClosures": "swisstopo Hiking Closures",
@@ -377,7 +380,9 @@
"railway-station": "Railway Station", "railway-station": "Railway Station",
"tram-stop": "Tram Stop", "tram-stop": "Tram Stop",
"bus-stop": "Bus Stop", "bus-stop": "Bus Stop",
"ferry": "Ferry" "ferry": "Ferry",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {

View File

@@ -231,7 +231,7 @@
}, },
"elevation": { "elevation": {
"button": "Request elevation data", "button": "Request elevation data",
"help": "Requesting elevation data will erase the existing elevation data, if any, and replace it with data from Mapbox.", "help": "Requesting elevation data will erase the existing elevation data, if any, and replace it with data from MapTiler.",
"help_no_selection": "Select a file item to request elevation data." "help_no_selection": "Select a file item to request elevation data."
}, },
"waypoint": { "waypoint": {
@@ -273,7 +273,7 @@
"new": "New custom layer", "new": "New custom layer",
"edit": "Edit custom layer", "edit": "Edit custom layer",
"urls": "URL(s)", "urls": "URL(s)",
"url_placeholder": "WMTS, WMS or Mapbox style JSON", "url_placeholder": "WMTS, WMS or MapLibre style JSON",
"max_zoom": "Max zoom", "max_zoom": "Max zoom",
"layer_type": "Layer type", "layer_type": "Layer type",
"basemap": "Basemap", "basemap": "Basemap",
@@ -282,6 +282,7 @@
"update": "Update layer" "update": "Update layer"
}, },
"opacity": "Overlay opacity", "opacity": "Overlay opacity",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "Basemaps", "basemaps": "Basemaps",
"overlays": "Overlays", "overlays": "Overlays",
@@ -299,8 +300,9 @@
"switzerland": "Switzerland", "switzerland": "Switzerland",
"united_kingdom": "United Kingdom", "united_kingdom": "United Kingdom",
"united_states": "United States", "united_states": "United States",
"mapboxOutdoors": "Mapbox Outdoors", "maptilerTopo": "MapTiler Topo",
"mapboxSatellite": "Mapbox Satellite", "maptilerOutdoors": "MapTiler Outdoors",
"maptilerSatellite": "MapTiler Satellite",
"openStreetMap": "OpenStreetMap", "openStreetMap": "OpenStreetMap",
"openTopoMap": "OpenTopoMap", "openTopoMap": "OpenTopoMap",
"openHikingMap": "OpenHikingMap", "openHikingMap": "OpenHikingMap",
@@ -325,6 +327,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Slope", "swisstopoSlope": "swisstopo Slope",
"swisstopoHiking": "swisstopo Hiking", "swisstopoHiking": "swisstopo Hiking",
"swisstopoHikingClosures": "swisstopo Hiking Closures", "swisstopoHikingClosures": "swisstopo Hiking Closures",
@@ -377,7 +381,9 @@
"railway-station": "Railway Station", "railway-station": "Railway Station",
"tram-stop": "Tram Stop", "tram-stop": "Tram Stop",
"bus-stop": "Bus Stop", "bus-stop": "Bus Stop",
"ferry": "Ferry" "ferry": "Ferry",
"maptiler-dem": "MapTiler DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {
@@ -518,7 +524,7 @@
}, },
"embedding": { "embedding": {
"title": "Create your own map", "title": "Create your own map",
"mapbox_token": "Mapbox access token", "maptiler_key": "MapTiler key",
"file_urls": "File URLs (separated by commas)", "file_urls": "File URLs (separated by commas)",
"drive_ids": "Google Drive file IDs (separated by commas)", "drive_ids": "Google Drive file IDs (separated by commas)",
"basemap": "Basemap", "basemap": "Basemap",

View File

@@ -2,7 +2,7 @@
"metadata": { "metadata": {
"home_title": "el editor online de archivos GPX", "home_title": "el editor online de archivos GPX",
"app_title": "app", "app_title": "app",
"embed_title": "El editor online de archivos GPX", "embed_title": " editor online de archivos GPX",
"help_title": "ayuda", "help_title": "ayuda",
"404_title": "página no encontrada", "404_title": "página no encontrada",
"description": "Mira, edita y crea archivos GPX online con planificación avanzada de rutas y herramientas de procesamiento de archivos, bonitos mapas y visualizaciones detalladas de datos." "description": "Mira, edita y crea archivos GPX online con planificación avanzada de rutas y herramientas de procesamiento de archivos, bonitos mapas y visualizaciones detalladas de datos."
@@ -282,6 +282,7 @@
"update": "Actualizar capa" "update": "Actualizar capa"
}, },
"opacity": "Opacidad de la capa superpuesta", "opacity": "Opacidad de la capa superpuesta",
"terrain": "Origen del terreno",
"label": { "label": {
"basemaps": "Mapas base", "basemaps": "Mapas base",
"overlays": "Capas", "overlays": "Capas",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "Gravel bikerouter.de", "bikerouterGravel": "Gravel bikerouter.de",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Slope", "swisstopoSlope": "swisstopo Slope",
"swisstopoHiking": "swisstopo Senderismo", "swisstopoHiking": "swisstopo Senderismo",
"swisstopoHikingClosures": "swisstopo Rutas Senderismo", "swisstopoHikingClosures": "swisstopo Rutas Senderismo",
@@ -377,7 +380,9 @@
"railway-station": "Estación de tren", "railway-station": "Estación de tren",
"tram-stop": "Parada de tranvía", "tram-stop": "Parada de tranvía",
"bus-stop": "Parada de autobús", "bus-stop": "Parada de autobús",
"ferry": "Ferri" "ferry": "Ferri",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {

View File

@@ -282,6 +282,7 @@
"update": "Eguneratu geruza" "update": "Eguneratu geruza"
}, },
"opacity": "Geruzaren opakutasuna", "opacity": "Geruzaren opakutasuna",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "Oinarrizko mapak", "basemaps": "Oinarrizko mapak",
"overlays": "Geruzak", "overlays": "Geruzak",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Malda", "swisstopoSlope": "swisstopo Malda",
"swisstopoHiking": "swisstopo Mendi ibilaldiak", "swisstopoHiking": "swisstopo Mendi ibilaldiak",
"swisstopoHikingClosures": "swisstopo Hiking Closures", "swisstopoHikingClosures": "swisstopo Hiking Closures",
@@ -377,7 +380,9 @@
"railway-station": "Tren geltokia", "railway-station": "Tren geltokia",
"tram-stop": "Tranbia geltokia", "tram-stop": "Tranbia geltokia",
"bus-stop": "Autobus geltokia", "bus-stop": "Autobus geltokia",
"ferry": "Ferria" "ferry": "Ferria",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {

View File

@@ -282,6 +282,7 @@
"update": "Päivitä karttataso" "update": "Päivitä karttataso"
}, },
"opacity": "Peitetason läpinäkyvyys", "opacity": "Peitetason läpinäkyvyys",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "Taustakartat", "basemaps": "Taustakartat",
"overlays": "Peitetasot", "overlays": "Peitetasot",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Rinnekaltevuus", "swisstopoSlope": "swisstopo Rinnekaltevuus",
"swisstopoHiking": "swisstopo Retkeilyreitit", "swisstopoHiking": "swisstopo Retkeilyreitit",
"swisstopoHikingClosures": "swisstopo Hiking Closures", "swisstopoHikingClosures": "swisstopo Hiking Closures",
@@ -377,7 +380,9 @@
"railway-station": "Rautatieasemat", "railway-station": "Rautatieasemat",
"tram-stop": "Raitiovaunupysäkit", "tram-stop": "Raitiovaunupysäkit",
"bus-stop": "Linja-autopysäkit", "bus-stop": "Linja-autopysäkit",
"ferry": "Lautat" "ferry": "Lautat",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {

View File

@@ -282,6 +282,7 @@
"update": "Mettre à jour la couche" "update": "Mettre à jour la couche"
}, },
"opacity": "Opacité de la surcouche", "opacity": "Opacité de la surcouche",
"terrain": "Source du relief",
"label": { "label": {
"basemaps": "Fonds de carte", "basemaps": "Fonds de carte",
"overlays": "Surcouches", "overlays": "Surcouches",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Relief",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Pente", "swisstopoSlope": "swisstopo Pente",
"swisstopoHiking": "swisstopo Randonnée", "swisstopoHiking": "swisstopo Randonnée",
"swisstopoHikingClosures": "swisstopo Fermetures de randonnée", "swisstopoHikingClosures": "swisstopo Fermetures de randonnée",
@@ -350,7 +353,7 @@
"eat-and-drink": "Nourriture et boissons", "eat-and-drink": "Nourriture et boissons",
"amenities": "Commodités", "amenities": "Commodités",
"toilets": "Toilettes", "toilets": "Toilettes",
"water": "Cours d'eau", "water": "Eau potable",
"shower": "Douche", "shower": "Douche",
"shelter": "Abri", "shelter": "Abri",
"cemetery": "Cimetière", "cemetery": "Cimetière",
@@ -377,7 +380,9 @@
"railway-station": "Gare", "railway-station": "Gare",
"tram-stop": "Arrêt de tram", "tram-stop": "Arrêt de tram",
"bus-stop": "Arrêt de bus", "bus-stop": "Arrêt de bus",
"ferry": "Ferry" "ferry": "Ferry",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {
@@ -443,7 +448,7 @@
"convenience_store": "Épicerie", "convenience_store": "Épicerie",
"crossing": "Croisement", "crossing": "Croisement",
"department_store": "Grand magasin", "department_store": "Grand magasin",
"drinking_water": "Cours d'eau", "drinking_water": "Eau potable",
"exit": "Sortie", "exit": "Sortie",
"lodge": "Refuge", "lodge": "Refuge",
"lodging": "Hébergement", "lodging": "Hébergement",
@@ -468,7 +473,7 @@
"summit": "Sommet", "summit": "Sommet",
"telephone": "Téléphone", "telephone": "Téléphone",
"tunnel": "Tunnel", "tunnel": "Tunnel",
"water_source": "Source d'eau" "water_source": "Point d'eau"
} }
}, },
"homepage": { "homepage": {

View File

@@ -282,6 +282,7 @@
"update": "Update layer" "update": "Update layer"
}, },
"opacity": "Overlay opacity", "opacity": "Overlay opacity",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "Basemaps", "basemaps": "Basemaps",
"overlays": "Overlays", "overlays": "Overlays",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Slope", "swisstopoSlope": "swisstopo Slope",
"swisstopoHiking": "swisstopo Hiking", "swisstopoHiking": "swisstopo Hiking",
"swisstopoHikingClosures": "swisstopo Hiking Closures", "swisstopoHikingClosures": "swisstopo Hiking Closures",
@@ -377,7 +380,9 @@
"railway-station": "Railway Station", "railway-station": "Railway Station",
"tram-stop": "Tram Stop", "tram-stop": "Tram Stop",
"bus-stop": "Bus Stop", "bus-stop": "Bus Stop",
"ferry": "Ferry" "ferry": "Ferry",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {

View File

@@ -282,6 +282,7 @@
"update": "Réteg feltöltése" "update": "Réteg feltöltése"
}, },
"opacity": "Átfedés átlátszósága", "opacity": "Átfedés átlátszósága",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "Alaptérkép", "basemaps": "Alaptérkép",
"overlays": "Térkép rétegek", "overlays": "Térkép rétegek",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "kerékpár és terepkerékpár út", "bikerouterGravel": "kerékpár és terepkerékpár út",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Lejtő", "swisstopoSlope": "swisstopo Lejtő",
"swisstopoHiking": "swisstopo Túra", "swisstopoHiking": "swisstopo Túra",
"swisstopoHikingClosures": "swisstopo túralezárások", "swisstopoHikingClosures": "swisstopo túralezárások",
@@ -377,7 +380,9 @@
"railway-station": "Vasútállomás", "railway-station": "Vasútállomás",
"tram-stop": "Villamos megálló", "tram-stop": "Villamos megálló",
"bus-stop": "Buszmegálló", "bus-stop": "Buszmegálló",
"ferry": "Komp" "ferry": "Komp",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {

View File

@@ -282,6 +282,7 @@
"update": "Perbarui lapisan" "update": "Perbarui lapisan"
}, },
"opacity": "Opasitas Overlay", "opacity": "Opasitas Overlay",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "Peta dasar", "basemaps": "Peta dasar",
"overlays": "Overlay", "overlays": "Overlay",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Kemiringan", "swisstopoSlope": "swisstopo Kemiringan",
"swisstopoHiking": "swisstopo Pendakian", "swisstopoHiking": "swisstopo Pendakian",
"swisstopoHikingClosures": "Penutupan Jalur Pendakian swisstopo", "swisstopoHikingClosures": "Penutupan Jalur Pendakian swisstopo",
@@ -377,7 +380,9 @@
"railway-station": "Stasiun kereta api", "railway-station": "Stasiun kereta api",
"tram-stop": "Halt trem", "tram-stop": "Halt trem",
"bus-stop": "Pemberhentian Bus", "bus-stop": "Pemberhentian Bus",
"ferry": "Feri" "ferry": "Feri",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {

View File

@@ -34,8 +34,8 @@
"elevation_profile": "Profilo altimetrico", "elevation_profile": "Profilo altimetrico",
"tree_file_view": "Vista ad albero", "tree_file_view": "Vista ad albero",
"switch_basemap": "Passa alla mappa di base precedente", "switch_basemap": "Passa alla mappa di base precedente",
"toggle_overlays": "Attiva/disattiva le sovrapposizioni", "toggle_overlays": "Attiva / disattiva le sovrapposizioni",
"toggle_3d": "Attiva/disattiva 3D", "toggle_3d": "Attiva / disattiva 3D",
"settings": "Impostazioni", "settings": "Impostazioni",
"distance_units": "Unità distanza", "distance_units": "Unità distanza",
"metric": "Metrico", "metric": "Metrico",
@@ -53,7 +53,7 @@
"street_view_source": "Sorgente della vista stradale", "street_view_source": "Sorgente della vista stradale",
"mapillary": "Mapillary", "mapillary": "Mapillary",
"google": "Google", "google": "Google",
"toggle_street_view": "Street View", "toggle_street_view": "Vista stradale",
"layers": "Livelli della mappa...", "layers": "Livelli della mappa...",
"distance_markers": "Indicatori di distanza", "distance_markers": "Indicatori di distanza",
"direction_markers": "Frecce direzionali", "direction_markers": "Frecce direzionali",
@@ -87,7 +87,7 @@
"tooltip": "Pianifica o modifica un percorsoo", "tooltip": "Pianifica o modifica un percorsoo",
"activity": "Attività", "activity": "Attività",
"use_routing": "Instradamento", "use_routing": "Instradamento",
"use_routing_tooltip": "Collega i punti di ancoraggio tramite la rete stradale o in linea retta se disabilitato", "use_routing_tooltip": "Collega i punti di ancoraggio tramite la rete stradale (o in linea retta se disabilitato)",
"allow_private": "Consenti strade private", "allow_private": "Consenti strade private",
"reverse": { "reverse": {
"button": "Inverti la traccia", "button": "Inverti la traccia",
@@ -235,18 +235,18 @@
"help_no_selection": "Seleziona un file per richiedere i dati di altitudine." "help_no_selection": "Seleziona un file per richiedere i dati di altitudine."
}, },
"waypoint": { "waypoint": {
"tooltip": "Creare e modificare punti di interesse", "tooltip": "Creare e modificare punti d'interesse",
"icon": "Icona", "icon": "Icona",
"link": "Collegamento", "link": "Collegamento",
"longitude": "Longitudine", "longitude": "Longitudine",
"latitude": "Latitudine", "latitude": "Latitudine",
"create": "Creare un punto di interesse", "create": "Creare un punto d'interesse",
"add": "Aggiungi punto di interesse al file", "add": "Aggiungi punto d'interesse al file",
"help": "Compila il modulo per creare un nuovo punto di interesse, oppure fai clic su uno esistente per modificarlo. Fare clic sulla mappa per inserire le coordinate o trascinare i punti di interesse per spostarli.", "help": "Compila il modulo per creare un nuovo punto d'interesse, oppure fai clic su uno esistente per modificarlo. Fare clic sulla mappa per inserire le coordinate o trascinare i punti d'interesse per spostarli.",
"help_no_selection": "Selezionare un file per creare o modificare punti di interesse." "help_no_selection": "Selezionare un file per creare o modificare punti d'interesse."
}, },
"reduce": { "reduce": {
"tooltip": "Riduci il numero di punti della traccia", "tooltip": "Riduci il numero di punti GPS",
"tolerance": "Tolleranza", "tolerance": "Tolleranza",
"number_of_points": "Numero di punti GPS", "number_of_points": "Numero di punti GPS",
"button": "Minimizza", "button": "Minimizza",
@@ -254,14 +254,14 @@
"help_no_selection": "Selezionare una traccia per ridurre il numero dei suoi punti GPS." "help_no_selection": "Selezionare una traccia per ridurre il numero dei suoi punti GPS."
}, },
"clean": { "clean": {
"tooltip": "Pulire i punti GPS e i punti di interesse con una selezione rettangolare", "tooltip": "Pulire i punti GPS e i punti d'interesse con una selezione rettangolare",
"delete_trackpoints": "Eliminare punti GPS", "delete_trackpoints": "Eliminare punti GPS",
"delete_waypoints": "Cancella punti d'interesse", "delete_waypoints": "Cancella punti d'interesse",
"delete_inside": "Elimina all'interno della selezione", "delete_inside": "Elimina all'interno della selezione",
"delete_outside": "Elimina fuori dalla selezione", "delete_outside": "Elimina fuori dalla selezione",
"button": "Elimina", "button": "Elimina",
"help": "Selezionare un'area rettangolare sulla mappa per rimuovere i punti GPS e i punti di interesse.", "help": "Selezionare un'area rettangolare sulla mappa per rimuovere i punti GPS e i punti d'interesse.",
"help_no_selection": "Seleziona una traccia per pulire i punti GPS e i punti di interesse." "help_no_selection": "Seleziona una traccia per pulire i punti GPS e i punti d'interesse."
} }
}, },
"layers": { "layers": {
@@ -273,7 +273,7 @@
"new": "Nuovo livello personalizzato", "new": "Nuovo livello personalizzato",
"edit": "Modifica livello personalizzato", "edit": "Modifica livello personalizzato",
"urls": "URL(s)", "urls": "URL(s)",
"url_placeholder": "WMTS, WMS o Mapbox stile JSON", "url_placeholder": "WMTS, WMS o JSON in stile Mapbox",
"max_zoom": "Zoom massimo", "max_zoom": "Zoom massimo",
"layer_type": "Tipo del layer", "layer_type": "Tipo del layer",
"basemap": "Mappa Base", "basemap": "Mappa Base",
@@ -282,6 +282,7 @@
"update": "Aggiorna livello" "update": "Aggiorna livello"
}, },
"opacity": "Opacità di sovrapposizione", "opacity": "Opacità di sovrapposizione",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "Mappe di base", "basemaps": "Mappe di base",
"overlays": "Sovrapposizioni", "overlays": "Sovrapposizioni",
@@ -309,7 +310,7 @@
"linz": "LINZ Topo", "linz": "LINZ Topo",
"linzTopo": "LINZ Topo50", "linzTopo": "LINZ Topo50",
"swisstopoRaster": "swisstopo Raster", "swisstopoRaster": "swisstopo Raster",
"swisstopoVector": "Swisstopo Vector", "swisstopoVector": "swisstopo Vector",
"swisstopoSatellite": "swisstopo Satellite", "swisstopoSatellite": "swisstopo Satellite",
"ignBe": "IGN Topo", "ignBe": "IGN Topo",
"ignFrPlan": "IGN Plan", "ignFrPlan": "IGN Plan",
@@ -318,25 +319,27 @@
"ignFrSatellite": "Satellitare IGN", "ignFrSatellite": "Satellitare IGN",
"ignEs": "IGN Topo", "ignEs": "IGN Topo",
"ignEsSatellite": "Satellitare IGN", "ignEsSatellite": "Satellitare IGN",
"ordnanceSurvey": "Sondaggio Ordnance", "ordnanceSurvey": "Ordnance Survey",
"norwayTopo": "Topografisk Norgeskart 4", "norwayTopo": "Topografisk Norgeskart 4",
"finlandTopo": "Carta topografica del vecchio Catasto svedese", "finlandTopo": "Lantmäteriverket Terrängkarta",
"bgMountains": "BGMountains", "bgMountains": "BGMountains",
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"swisstopoSlope": "Carta topografica Svizzera Pendenza", "mapterhornHillshade": "Mapterhorn Hillshade",
"swisstopoHiking": "Carta topografica Svedese Escursione", "openRailwayMap": "OpenRailwayMap",
"swisstopoHikingClosures": "Carta topografica Svizzera Fine escursione", "swisstopoSlope": "swisstopo Pendenza",
"swisstopoCycling": "Carta topografica Svizzera Ciclabile", "swisstopoHiking": "swisstopo Escursione",
"swisstopoCyclingClosures": "Carta topografica Svizzera fine ciclabile", "swisstopoHikingClosures": "swisstopo Fine escursione",
"swisstopoMountainBike": "Carta topografica Svizzera MTB", "swisstopoCycling": "swisstopo Ciclabile",
"swisstopoMountainBikeClosures": "Carta topografica Svizzera fine MTB", "swisstopoCyclingClosures": "swisstopo Fine ciclabile",
"swisstopoSkiTouring": "Carta topografica Svizzera pista sci", "swisstopoMountainBike": "swisstopo MTB",
"swisstopoMountainBikeClosures": "swisstopo Fine MTB",
"swisstopoSkiTouring": "swisstopo Sci Alpinismo",
"ignFrCadastre": "IGN Catasto", "ignFrCadastre": "IGN Catasto",
"ignSlope": "Pendenza IGN", "ignSlope": "IGN Pendenza",
"ignSkiTouring": "IGN Sciescursionismo", "ignSkiTouring": "IGN Sci Alpinismo",
"waymarked_trails": "Waymarked Trails", "waymarked_trails": "Sentieri Segnalati",
"waymarkedTrailsHiking": "Escursionismo", "waymarkedTrailsHiking": "Escursionismo",
"waymarkedTrailsCycling": "Ciclismo", "waymarkedTrailsCycling": "Ciclismo",
"waymarkedTrailsMTB": "MTB", "waymarkedTrailsMTB": "MTB",
@@ -377,7 +380,9 @@
"railway-station": "Stazione ferroviaria", "railway-station": "Stazione ferroviaria",
"tram-stop": "Fermata del tram", "tram-stop": "Fermata del tram",
"bus-stop": "Fermata dell'autobus", "bus-stop": "Fermata dell'autobus",
"ferry": "Traghetto" "ferry": "Traghetto",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {
@@ -406,11 +411,11 @@
"feet": "ft", "feet": "ft",
"kilometers": "km", "kilometers": "km",
"miles": "mi", "miles": "mi",
"nautical_miles": "nm", "nautical_miles": "NM",
"celsius": "°C", "celsius": "°C",
"fahrenheit": "°F", "fahrenheit": "°F",
"kilometers_per_hour": "km/h", "kilometers_per_hour": "km/h",
"miles_per_hour": "mph", "miles_per_hour": "mi/h",
"minutes_per_kilometer": "min/km", "minutes_per_kilometer": "min/km",
"minutes_per_mile": "min/mi", "minutes_per_mile": "min/mi",
"minutes_per_nautical_mile": "min/nm", "minutes_per_nautical_mile": "min/nm",
@@ -426,8 +431,8 @@
"tracks": "Tracce", "tracks": "Tracce",
"segment": "Segmento", "segment": "Segmento",
"segments": "Segmenti", "segments": "Segmenti",
"waypoint": "Punto di interesse", "waypoint": "Punto d'interesse",
"waypoints": "Punti di interesse", "waypoints": "Punti d'interesse",
"symbol": { "symbol": {
"alert": "Avviso", "alert": "Avviso",
"anchor": "Ancora", "anchor": "Ancora",
@@ -483,13 +488,13 @@
"email": "Email", "email": "Email",
"contribute": "Contribuire", "contribute": "Contribuire",
"supported_by": "supportato da", "supported_by": "supportato da",
"support_button": "Supporto di gpx.studio su Ko-fi", "support_button": "Supporta gpx.studio su Ko-fi",
"route_planning": "Pianificazione del percorso", "route_planning": "Pianificazione del percorso",
"route_planning_description": "Un'interfaccia intuitiva per creare itinerari su misura per ogni sport, basati sui dati OpenStreetMap.", "route_planning_description": "Un'interfaccia intuitiva per creare itinerari su misura per ogni sport, basata sui dati OpenStreetMap.",
"file_processing": "Elaborazione avanzata dei file", "file_processing": "Elaborazione avanzata dei file",
"file_processing_description": "Una serie di strumenti per eseguire tutte le attività comuni di elaborazione dei file e che possono essere applicati a più file contemporaneamente.", "file_processing_description": "Una serie di strumenti per eseguire tutte le attività comuni di elaborazione dei file e che possono essere applicati a più file contemporaneamente.",
"maps": "Mappe globali e locali", "maps": "Mappe globali e locali",
"maps_description": "Una vasta collezione di mappe di base, sovrapposizioni e punti d'interesse per aiutarti a creare la tua prossima avventura all'aperto o visualizzare il tuo ultimo risultato.", "maps_description": "Una vasta collezione di mappe di base, sovrapposizioni e punti d'interesse per aiutarti a creare la tua prossima avventura all'aperto o visualizzare la tua ultima impresa.",
"data_visualization": "Visualizzazione dei dati", "data_visualization": "Visualizzazione dei dati",
"data_visualization_description": "Un profilo di elevazione interattivo con statistiche dettagliate per analizzare attività registrate e obiettivi futuri.", "data_visualization_description": "Un profilo di elevazione interattivo con statistiche dettagliate per analizzare attività registrate e obiettivi futuri.",
"identity": "Gratuito, senza pubblicità e open source", "identity": "Gratuito, senza pubblicità e open source",

View File

@@ -282,6 +282,7 @@
"update": "레이어 갱신" "update": "레이어 갱신"
}, },
"opacity": "오버레이 투명도", "opacity": "오버레이 투명도",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "배경 지도", "basemaps": "배경 지도",
"overlays": "오버레이", "overlays": "오버레이",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Slope", "swisstopoSlope": "swisstopo Slope",
"swisstopoHiking": "swisstopo Hiking", "swisstopoHiking": "swisstopo Hiking",
"swisstopoHikingClosures": "swisstopo Hiking Closures", "swisstopoHikingClosures": "swisstopo Hiking Closures",
@@ -377,7 +380,9 @@
"railway-station": "철도역", "railway-station": "철도역",
"tram-stop": "트램 정류장", "tram-stop": "트램 정류장",
"bus-stop": "버스 정류장", "bus-stop": "버스 정류장",
"ferry": "페리" "ferry": "페리",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {

View File

@@ -282,6 +282,7 @@
"update": "Naujinti sluoksnį" "update": "Naujinti sluoksnį"
}, },
"opacity": "Sluoksnio skaidrumas", "opacity": "Sluoksnio skaidrumas",
"terrain": "Terrain source",
"label": { "label": {
"basemaps": "Pagrindo žemėlapiai", "basemaps": "Pagrindo žemėlapiai",
"overlays": "Sluoksniai", "overlays": "Sluoksniai",
@@ -325,6 +326,8 @@
"usgs": "USGS", "usgs": "USGS",
"bikerouterGravel": "bikerouter.de Gravel", "bikerouterGravel": "bikerouter.de Gravel",
"cyclOSMlite": "CyclOSM Lite", "cyclOSMlite": "CyclOSM Lite",
"mapterhornHillshade": "Mapterhorn Hillshade",
"openRailwayMap": "OpenRailwayMap",
"swisstopoSlope": "swisstopo Slope", "swisstopoSlope": "swisstopo Slope",
"swisstopoHiking": "swisstopo Hiking", "swisstopoHiking": "swisstopo Hiking",
"swisstopoHikingClosures": "swisstopo Hiking Closures", "swisstopoHikingClosures": "swisstopo Hiking Closures",
@@ -377,7 +380,9 @@
"railway-station": "Geležinkelio stotis", "railway-station": "Geležinkelio stotis",
"tram-stop": "Tramvajaus stotelė", "tram-stop": "Tramvajaus stotelė",
"bus-stop": "Autobusų stotelė", "bus-stop": "Autobusų stotelė",
"ferry": "Keltas" "ferry": "Keltas",
"mapbox-dem": "Mapbox DEM",
"mapterhorn": "Mapterhorn"
} }
}, },
"chart": { "chart": {

Some files were not shown because too many files have changed in this diff Show More