mirror of
https://github.com/gpxstudio/gpx.studio.git
synced 2025-09-02 00:32:33 +00:00
move routing stuff
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { currentTool, reverseSelectedFiles, Tool } from '$lib/stores';
|
||||
import Routing from './routing/Routing.svelte';
|
||||
import Routing from '$lib/components/routing/Routing.svelte';
|
||||
import ToolbarItem from './ToolbarItem.svelte';
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
|
@@ -1,206 +0,0 @@
|
||||
<script lang="ts">
|
||||
import ToolbarItemMenu from '../ToolbarItemMenu.svelte';
|
||||
import * as Card from '$lib/components/ui/card';
|
||||
import * as Select from '$lib/components/ui/select';
|
||||
import { Switch } from '$lib/components/ui/switch';
|
||||
import { Label } from '$lib/components/ui/label/index.js';
|
||||
import * as Alert from '$lib/components/ui/alert';
|
||||
import { CircleHelp } from 'lucide-svelte';
|
||||
|
||||
import { map, selectedFiles, applyToFile } from '$lib/stores';
|
||||
import { AnchorPointHierarchy, getMarker, route } from './routing';
|
||||
import { onDestroy } from 'svelte';
|
||||
import mapboxgl from 'mapbox-gl';
|
||||
import KDBush from 'kdbush';
|
||||
|
||||
import type { GPXFile } from 'gpx';
|
||||
|
||||
import { _ } from 'svelte-i18n';
|
||||
|
||||
let brouterProfiles: { [key: string]: string } = {
|
||||
bike: 'Trekking-dry',
|
||||
racing_bike: 'fastbike',
|
||||
mountain_bike: 'MTB',
|
||||
foot: 'Hiking-Alpine-SAC6',
|
||||
motorcycle: 'Car-FastEco',
|
||||
water: 'river',
|
||||
railway: 'rail'
|
||||
};
|
||||
let routingProfile = {
|
||||
value: 'bike',
|
||||
label: $_('toolbar.routing.activities.bike')
|
||||
};
|
||||
let routing = true;
|
||||
let privateRoads = false;
|
||||
|
||||
let anchorPointHierarchy: AnchorPointHierarchy | null = null;
|
||||
let markers: mapboxgl.Marker[] = [];
|
||||
let file: GPXFile | null = null;
|
||||
let kdbush: KDBush | null = null;
|
||||
|
||||
function toggleMarkersForZoomLevelAndBounds() {
|
||||
if ($map) {
|
||||
let zoom = $map.getZoom();
|
||||
markers.forEach((marker) => {
|
||||
if (marker._simplified.zoom <= zoom && $map.getBounds().contains(marker.getLngLat())) {
|
||||
marker.addTo($map);
|
||||
} else {
|
||||
marker.remove();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function extendFile(e: mapboxgl.MapMouseEvent) {
|
||||
if (file && anchorPointHierarchy && anchorPointHierarchy.points.length > 0) {
|
||||
let lastPoint = anchorPointHierarchy.points[anchorPointHierarchy.points.length - 1];
|
||||
let newPoint = {
|
||||
lon: e.lngLat.lng,
|
||||
lat: e.lngLat.lat
|
||||
};
|
||||
let response = await route(
|
||||
[lastPoint.point.getCoordinates(), newPoint],
|
||||
brouterProfiles[routingProfile.value],
|
||||
privateRoads,
|
||||
routing
|
||||
);
|
||||
applyToFile(file, (f) => f.append(response), true);
|
||||
}
|
||||
}
|
||||
|
||||
let insertableMarker: mapboxgl.Marker | null = null;
|
||||
function moveInsertableMarker(e: mapboxgl.MapMouseEvent) {
|
||||
if (insertableMarker && kdbush && $map) {
|
||||
let bounds = $map.getBounds();
|
||||
let latLngDistance = Math.max(
|
||||
Math.abs(bounds.getNorth() - bounds.getSouth()),
|
||||
Math.abs(bounds.getEast() - bounds.getWest())
|
||||
);
|
||||
if (kdbush.within(e.lngLat.lng, e.lngLat.lat, latLngDistance / 200).length > 0) {
|
||||
insertableMarker.setLngLat(e.lngLat);
|
||||
} else {
|
||||
insertableMarker.remove();
|
||||
insertableMarker = null;
|
||||
$map.off('mousemove', moveInsertableMarker);
|
||||
}
|
||||
}
|
||||
}
|
||||
function showInsertableMarker(e: mapboxgl.MapMouseEvent) {
|
||||
if ($map && !insertableMarker) {
|
||||
insertableMarker = getMarker({
|
||||
lon: e.lngLat.lng,
|
||||
lat: e.lngLat.lat
|
||||
});
|
||||
insertableMarker.addTo($map);
|
||||
$map.on('mousemove', moveInsertableMarker);
|
||||
}
|
||||
}
|
||||
|
||||
function clean() {
|
||||
markers.forEach((marker) => {
|
||||
marker.remove();
|
||||
});
|
||||
markers = [];
|
||||
if ($map) {
|
||||
$map.off('zoom', toggleMarkersForZoomLevelAndBounds);
|
||||
$map.off('move', toggleMarkersForZoomLevelAndBounds);
|
||||
$map.off('click', extendFile);
|
||||
if (file) {
|
||||
$map.off('mouseover', file._data.layerId, showInsertableMarker);
|
||||
}
|
||||
if (insertableMarker) {
|
||||
insertableMarker.remove();
|
||||
}
|
||||
}
|
||||
kdbush = null;
|
||||
}
|
||||
|
||||
$: if ($selectedFiles.size == 1) {
|
||||
let selectedFile = $selectedFiles.values().next().value;
|
||||
|
||||
if (selectedFile !== file) {
|
||||
clean();
|
||||
file = selectedFile;
|
||||
} else {
|
||||
// update markers
|
||||
}
|
||||
} else {
|
||||
clean();
|
||||
file = null;
|
||||
}
|
||||
|
||||
$: if ($map && file) {
|
||||
// record time
|
||||
let start = performance.now();
|
||||
anchorPointHierarchy = AnchorPointHierarchy.create(file);
|
||||
// record time
|
||||
let end = performance.now();
|
||||
console.log('Time to create anchor points: ' + (end - start) + 'ms');
|
||||
|
||||
markers = anchorPointHierarchy.getMarkers();
|
||||
|
||||
toggleMarkersForZoomLevelAndBounds();
|
||||
$map.on('zoom', toggleMarkersForZoomLevelAndBounds);
|
||||
$map.on('move', toggleMarkersForZoomLevelAndBounds);
|
||||
$map.on('click', extendFile);
|
||||
$map.on('mouseover', file._data.layerId, showInsertableMarker);
|
||||
|
||||
let points = file.getTrackPoints();
|
||||
|
||||
start = performance.now();
|
||||
kdbush = new KDBush(points.length);
|
||||
for (let i = 0; i < points.length; i++) {
|
||||
kdbush.add(points[i].getLongitude(), points[i].getLatitude());
|
||||
}
|
||||
kdbush.finish();
|
||||
end = performance.now();
|
||||
console.log('Time to create kdbush: ' + (end - start) + 'ms');
|
||||
}
|
||||
|
||||
onDestroy(() => {
|
||||
clean();
|
||||
});
|
||||
</script>
|
||||
|
||||
<ToolbarItemMenu>
|
||||
<Card.Root>
|
||||
<Card.Content class="p-4 flex flex-col gap-4">
|
||||
<div class="w-full flex flex-row justify-between items-center gap-2">
|
||||
<Label>{$_('toolbar.routing.activity')}</Label>
|
||||
<Select.Root bind:selected={routingProfile}>
|
||||
<Select.Trigger class="h-8 w-40">
|
||||
<Select.Value />
|
||||
</Select.Trigger>
|
||||
<Select.Content>
|
||||
{#each Object.keys(brouterProfiles) as profile}
|
||||
<Select.Item value={profile}
|
||||
>{$_(`toolbar.routing.activities.${profile}`)}</Select.Item
|
||||
>
|
||||
{/each}
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
</div>
|
||||
<div class="w-full flex flex-row justify-between items-center gap-2">
|
||||
<Label for="routing">{$_('toolbar.routing.use_routing')}</Label>
|
||||
<Switch id="routing" class="scale-90" bind:checked={routing} />
|
||||
</div>
|
||||
<div class="w-full flex flex-row justify-between items-center gap-2">
|
||||
<Label for="private">{$_('toolbar.routing.allow_private')}</Label>
|
||||
<Switch id="private" class="scale-90" bind:checked={privateRoads} />
|
||||
</div>
|
||||
<Alert.Root class="max-w-64">
|
||||
<CircleHelp size="16" />
|
||||
<!-- <Alert.Title>Heads up!</Alert.Title> -->
|
||||
<Alert.Description>
|
||||
{#if $selectedFiles.size > 1}
|
||||
<div>{$_('toolbar.routing.help_multiple_files')}</div>
|
||||
{:else if $selectedFiles.size == 0}
|
||||
<div>{$_('toolbar.routing.help_no_file')}</div>
|
||||
{:else}
|
||||
<div>{$_('toolbar.routing.help')}</div>
|
||||
{/if}
|
||||
</Alert.Description>
|
||||
</Alert.Root>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
</ToolbarItemMenu>
|
@@ -1,192 +0,0 @@
|
||||
import type { Coordinates, GPXFile } from "gpx";
|
||||
import { TrackPoint } from "gpx";
|
||||
import mapboxgl from "mapbox-gl";
|
||||
|
||||
export function getMarker(coordinates: Coordinates, draggable: boolean = false): mapboxgl.Marker {
|
||||
let element = document.createElement('div');
|
||||
element.className = `h-3 w-3 rounded-full bg-background border-2 border-black cursor-pointer`;
|
||||
return new mapboxgl.Marker({
|
||||
draggable,
|
||||
element
|
||||
}).setLngLat(coordinates);
|
||||
}
|
||||
|
||||
export type SimplifiedTrackPoint = { point: TrackPoint, index: number, distance?: number, segment?: number, zoom?: number };
|
||||
|
||||
export class AnchorPointHierarchy {
|
||||
points: SimplifiedTrackPoint[];
|
||||
|
||||
constructor() {
|
||||
this.points = [];
|
||||
}
|
||||
|
||||
getMarkers(): mapboxgl.Marker[] {
|
||||
let markers = [];
|
||||
for (let point of this.points) {
|
||||
let marker = getMarker(point.point.getCoordinates(), true);
|
||||
Object.defineProperty(marker, '_simplified', { value: point });
|
||||
markers.push(marker);
|
||||
}
|
||||
return markers;
|
||||
}
|
||||
|
||||
static create(file: GPXFile, epsilon: number = 50): AnchorPointHierarchy {
|
||||
let hierarchy = new AnchorPointHierarchy();
|
||||
|
||||
let s = 0;
|
||||
for (let track of file.getChildren()) {
|
||||
for (let segment of track.getChildren()) {
|
||||
let points = segment.trkpt;
|
||||
let simplified = ramerDouglasPeucker(points, epsilon);
|
||||
// Assign segment number to each point
|
||||
simplified.forEach((point) => {
|
||||
point.segment = s;
|
||||
point.zoom = getZoomLevelForDistance(point.point.getLatitude(), point.distance);
|
||||
hierarchy.points.push(point);
|
||||
});
|
||||
s++;
|
||||
}
|
||||
}
|
||||
|
||||
return hierarchy;
|
||||
}
|
||||
}
|
||||
|
||||
function getZoomLevelForDistance(latitude: number, distance?: number): number {
|
||||
if (distance === undefined) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const rad = Math.PI / 180;
|
||||
const lat = latitude * rad;
|
||||
|
||||
return Math.min(20, Math.max(0, Math.floor(Math.log2((earthRadius * Math.cos(lat)) / distance))));
|
||||
}
|
||||
|
||||
function ramerDouglasPeucker(points: TrackPoint[], epsilon: number, start: number = 0, end: number = points.length - 1): SimplifiedTrackPoint[] {
|
||||
let simplified = [{
|
||||
point: points[start],
|
||||
index: start,
|
||||
|
||||
}];
|
||||
ramerDouglasPeuckerRecursive(points, epsilon, start, end, simplified);
|
||||
simplified.push({
|
||||
point: points[end],
|
||||
index: end
|
||||
});
|
||||
return simplified;
|
||||
}
|
||||
|
||||
function ramerDouglasPeuckerRecursive(points: TrackPoint[], epsilon: number, start: number, end: number, simplified: SimplifiedTrackPoint[]) {
|
||||
let largest = {
|
||||
index: 0,
|
||||
distance: 0
|
||||
};
|
||||
|
||||
for (let i = start + 1; i < end; i++) {
|
||||
let distance = crossarc(points[start].getCoordinates(), points[end].getCoordinates(), points[i].getCoordinates());
|
||||
if (distance > largest.distance) {
|
||||
largest.index = i;
|
||||
largest.distance = distance;
|
||||
}
|
||||
}
|
||||
|
||||
if (largest.distance > epsilon) {
|
||||
ramerDouglasPeuckerRecursive(points, epsilon, start, largest.index, simplified);
|
||||
simplified.push({ point: points[largest.index], index: largest.index, distance: largest.distance });
|
||||
ramerDouglasPeuckerRecursive(points, epsilon, largest.index, end, simplified);
|
||||
}
|
||||
}
|
||||
|
||||
const earthRadius = 6371008.8;
|
||||
|
||||
function crossarc(coord1: Coordinates, coord2: Coordinates, coord3: Coordinates): number {
|
||||
// Calculates the shortest distance in meters
|
||||
// between an arc (defined by p1 and p2) and a third point, p3.
|
||||
// Input lat1,lon1,lat2,lon2,lat3,lon3 in degrees.
|
||||
|
||||
const rad = Math.PI / 180;
|
||||
const lat1 = coord1.lat * rad;
|
||||
const lat2 = coord2.lat * rad;
|
||||
const lat3 = coord3.lat * rad;
|
||||
|
||||
const lon1 = coord1.lon * rad;
|
||||
const lon2 = coord2.lon * rad;
|
||||
const lon3 = coord3.lon * rad;
|
||||
|
||||
// Prerequisites for the formulas
|
||||
const bear12 = bearing(lat1, lon1, lat2, lon2);
|
||||
const bear13 = bearing(lat1, lon1, lat3, lon3);
|
||||
let dis13 = distance(lat1, lon1, lat3, lon3);
|
||||
|
||||
let diff = Math.abs(bear13 - bear12);
|
||||
if (diff > Math.PI) {
|
||||
diff = 2 * Math.PI - diff;
|
||||
}
|
||||
|
||||
// Is relative bearing obtuse?
|
||||
if (diff > (Math.PI / 2)) {
|
||||
return dis13;
|
||||
}
|
||||
|
||||
// Find the cross-track distance.
|
||||
let dxt = Math.asin(Math.sin(dis13 / earthRadius) * Math.sin(bear13 - bear12)) * earthRadius;
|
||||
|
||||
// Is p4 beyond the arc?
|
||||
let dis12 = distance(lat1, lon1, lat2, lon2);
|
||||
let dis14 = Math.acos(Math.cos(dis13 / earthRadius) / Math.cos(dxt / earthRadius)) * earthRadius;
|
||||
if (dis14 > dis12) {
|
||||
return distance(lat2, lon2, lat3, lon3);
|
||||
} else {
|
||||
return Math.abs(dxt);
|
||||
}
|
||||
}
|
||||
|
||||
function distance(latA: number, lonA: number, latB: number, lonB: number): number {
|
||||
// Finds the distance between two lat / lon points.
|
||||
return Math.acos(Math.sin(latA) * Math.sin(latB) + Math.cos(latA) * Math.cos(latB) * Math.cos(lonB - lonA)) * earthRadius;
|
||||
}
|
||||
|
||||
|
||||
function bearing(latA: number, lonA: number, latB: number, lonB: number): number {
|
||||
// Finds the bearing from one lat / lon point to another.
|
||||
return Math.atan2(Math.sin(lonB - lonA) * Math.cos(latB),
|
||||
Math.cos(latA) * Math.sin(latB) - Math.sin(latA) * Math.cos(latB) * Math.cos(lonB - lonA));
|
||||
}
|
||||
|
||||
export function route(points: Coordinates[], brouterProfile: string, privateRoads: boolean, routing: boolean): Promise<TrackPoint[]> {
|
||||
if (routing) {
|
||||
return getRoute(points, brouterProfile, privateRoads);
|
||||
} else {
|
||||
return new Promise((resolve) => {
|
||||
resolve(points.map(point => new TrackPoint({
|
||||
attributes: {
|
||||
lat: point.lat,
|
||||
lon: point.lon
|
||||
}
|
||||
})));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function getRoute(points: Coordinates[], brouterProfile: string, privateRoads: boolean): Promise<TrackPoint[]> {
|
||||
let url = `https://routing.gpx.studio?lonlats=${points.map(point => `${point.lon},${point.lat}`).join('|')}&profile=${brouterProfile + (privateRoads ? '-private' : '')}&format=geojson&alternativeidx=0`;
|
||||
|
||||
let response = await fetch(url);
|
||||
let geojson = await response.json();
|
||||
|
||||
let route: TrackPoint[] = [];
|
||||
let coordinates = geojson.features[0].geometry.coordinates;
|
||||
for (let i = 0; i < coordinates.length; i++) {
|
||||
let coord = coordinates[i];
|
||||
route.push(new TrackPoint({
|
||||
attributes: {
|
||||
lat: coord[1],
|
||||
lon: coord[0]
|
||||
},
|
||||
ele: coord[2] ?? undefined
|
||||
}));
|
||||
}
|
||||
|
||||
return route;
|
||||
}
|
Reference in New Issue
Block a user