move routing files

This commit is contained in:
vcoppe
2024-04-28 17:50:39 +02:00
parent 031977b801
commit 6b201d8341
5 changed files with 1 additions and 1 deletions

View File

@@ -0,0 +1,124 @@
<script lang="ts">
import ToolbarItemMenu from '$lib/components/toolbar/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 { currentTool, files, getFileStore, map, selectedFiles, Tool } from '$lib/stores';
import { brouterProfiles, privateRoads, routing, routingProfile } from './Routing';
import { _ } from 'svelte-i18n';
import { get, type Writable } from 'svelte/store';
import type { GPXFile } from 'gpx';
import { RoutingControls } from './RoutingControls';
import RoutingControlPopup from './RoutingControlPopup.svelte';
import { onMount } from 'svelte';
import mapboxgl from 'mapbox-gl';
let routingControls: Map<Writable<GPXFile>, RoutingControls> = new Map();
let popupElement: HTMLElement;
let popup: mapboxgl.Popup | null = null;
let selectedFile: Writable<GPXFile> | null = null;
let active = false;
$: if ($map && $files) {
// remove controls for deleted files
routingControls.forEach((controls, file) => {
if (!get(files).includes(file)) {
controls.remove();
routingControls.delete(file);
}
});
}
$: active = $currentTool === Tool.ROUTING;
$: if ($map && $selectedFiles) {
// update selected file
if ($selectedFiles.size == 0 || $selectedFiles.size > 1 || !active) {
if (selectedFile) {
routingControls.get(selectedFile)?.remove();
}
selectedFile = null;
} else {
let newSelectedFile = get(selectedFiles).values().next().value;
let newSelectedFileStore = getFileStore(newSelectedFile);
if (selectedFile !== newSelectedFileStore) {
if (selectedFile) {
routingControls.get(selectedFile)?.remove();
}
selectedFile = newSelectedFileStore;
}
}
}
$: if ($map && selectedFile) {
if (!routingControls.has(selectedFile)) {
routingControls.set(
selectedFile,
new RoutingControls(get(map), selectedFile, popup, popupElement)
);
} else {
routingControls.get(selectedFile)?.add();
}
}
onMount(() => {
popup = new mapboxgl.Popup({
closeButton: false,
maxWidth: undefined
});
popup.setDOMContent(popupElement);
popupElement.classList.remove('hidden');
});
</script>
{#if active}
<ToolbarItemMenu>
<Card.Root class="border-none">
<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>
{/if}
<RoutingControlPopup bind:element={popupElement} />

View File

@@ -0,0 +1,89 @@
import type { Coordinates } from "gpx";
import { TrackPoint } from "gpx";
import { get, writable } from "svelte/store";
import { _ } from "svelte-i18n";
export const brouterProfiles: { [key: string]: string } = {
bike: 'Trekking-dry',
racing_bike: 'fastbike',
mountain_bike: 'MTB',
foot: 'Hiking-Alpine-SAC6',
motorcycle: 'Car-FastEco',
water: 'river',
railway: 'rail'
};
export const routingProfile = writable({
value: 'bike',
label: get(_)('toolbar.routing.activities.bike')
});
export const routing = writable(true);
export const privateRoads = writable(false);
export function route(points: Coordinates[]): Promise<TrackPoint[]> {
if (get(routing)) {
return getRoute(points, brouterProfiles[get(routingProfile).value], get(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.toFixed(8)},${point.lat.toFixed(8)}`).join('|')}&profile=${brouterProfile + (privateRoads ? '-private' : '')}&format=geojson&alternativeidx=0`;
let response = await fetch(url);
// Check if the response is ok
if (!response.ok) {
throw new Error(`${await response.text()}`);
}
let geojson = await response.json();
let route: TrackPoint[] = [];
let coordinates = geojson.features[0].geometry.coordinates;
let messages = geojson.features[0].properties.messages;
const lngIdx = messages[0].indexOf("Longitude");
const latIdx = messages[0].indexOf("Latitude");
const tagIdx = messages[0].indexOf("WayTags");
let messageIdx = 1;
let surface = getSurface(messages[messageIdx][tagIdx]);
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
}));
route[route.length - 1].setSurface(surface)
if (messageIdx < messages.length &&
coordinates[i][0] == Number(messages[messageIdx][lngIdx]) / 1000000 &&
coordinates[i][1] == Number(messages[messageIdx][latIdx]) / 1000000) {
messageIdx++;
if (messageIdx == messages.length) surface = "unknown";
else surface = getSurface(messages[messageIdx][tagIdx]);
}
}
return route;
}
function getSurface(message: string): string {
const fields = message.split(" ");
for (let i = 0; i < fields.length; i++) if (fields[i].startsWith("surface=")) {
return fields[i].substring(8);
}
return "unknown";
};

View File

@@ -0,0 +1,22 @@
<script lang="ts">
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { Trash2 } from 'lucide-svelte';
import { _ } from 'svelte-i18n';
export let element: HTMLElement;
</script>
<div bind:this={element} class="hidden">
<Card.Root class="border-none shadow-md text-base">
<Card.Content class="flex flex-col p-1">
<Button
class="w-full px-2 py-1 h-6 justify-start"
variant="ghost"
on:click={() => element.dispatchEvent(new CustomEvent('delete'))}
><Trash2 size="16" class="mr-1" /> {$_('menu.delete')}</Button
>
</Card.Content>
</Card.Root>
</div>

View File

@@ -0,0 +1,447 @@
import { distance, type Coordinates, type GPXFile, type TrackSegment, TrackPoint } from "gpx";
import { get, type Writable } from "svelte/store";
import { computeAnchorPoints, type SimplifiedTrackPoint } from "./Simplify";
import mapboxgl from "mapbox-gl";
import { route } from "./Routing";
import { applyToFileElement } from "$lib/stores";
import { toast } from "svelte-sonner";
import { _ } from "svelte-i18n";
export class RoutingControls {
map: mapboxgl.Map;
file: Writable<GPXFile>;
markers: mapboxgl.Marker[] = [];
shownMarkers: mapboxgl.Marker[] = [];
popup: mapboxgl.Popup;
popupElement: HTMLElement;
temporaryAnchor: SimplifiedTrackPoint;
unsubscribe: () => void = () => { };
toggleMarkersForZoomLevelAndBoundsBinded: () => void = this.toggleMarkersForZoomLevelAndBounds.bind(this);
showTemporaryAnchorBinded: (e: any) => void = this.showTemporaryAnchor.bind(this);
hideTemporaryAnchorBinded: (e: any) => void = this.hideTemporaryAnchor.bind(this);
appendAnchorBinded: (e: mapboxgl.MapMouseEvent) => void = this.appendAnchor.bind(this);
constructor(map: mapboxgl.Map, file: Writable<GPXFile>, popup: mapboxgl.Popup, popupElement: HTMLElement) {
this.map = map;
this.file = file;
this.popup = popup;
this.popupElement = popupElement;
this.temporaryAnchor = {
point: new TrackPoint({
attributes: {
lon: 0,
lat: 0
}
}),
zoom: 0
};
this.createMarker(this.temporaryAnchor);
let marker = this.markers.pop(); // Remove the temporary anchor from the markers list
marker.getElement().classList.remove('z-10'); // Show below the other markers
Object.defineProperty(marker, '_temporary', {
value: true
});
this.add();
}
add() {
this.map.on('zoom', this.toggleMarkersForZoomLevelAndBoundsBinded);
this.map.on('move', this.toggleMarkersForZoomLevelAndBoundsBinded);
this.map.on('click', this.appendAnchorBinded);
this.map.on('mousemove', get(this.file)._data.layerId, this.showTemporaryAnchorBinded);
this.unsubscribe = this.file.subscribe(this.updateControls.bind(this));
}
updateControls() { // Update the markers when the file changes
for (let segment of get(this.file).getSegments()) {
if (!segment._data.anchors) { // New segment, create anchors for it
computeAnchorPoints(segment);
this.createMarkers(segment);
continue;
}
let anchors = segment._data.anchors;
for (let i = 0; i < anchors.length;) {
let anchor = anchors[i];
if (anchor.point._data.index >= segment.trkpt.length || anchor.point !== segment.trkpt[anchor.point._data.index]) { // Point does not exist anymore, remove the anchor
anchors.splice(i, 1);
this.markers[i].remove();
this.markers.splice(i, 1);
continue;
}
i++;
}
}
this.toggleMarkersForZoomLevelAndBounds();
}
remove() {
for (let marker of this.markers) {
marker.remove();
}
this.map.off('zoom', this.toggleMarkersForZoomLevelAndBoundsBinded);
this.map.off('move', this.toggleMarkersForZoomLevelAndBoundsBinded);
this.map.off('click', this.appendAnchorBinded);
this.map.off('mousemove', get(this.file)._data.layerId, this.showTemporaryAnchorBinded);
this.map.off('mousemove', this.hideTemporaryAnchorBinded);
this.unsubscribe();
}
createMarkers(segment: TrackSegment) {
for (let anchor of segment._data.anchors) {
this.createMarker(anchor);
}
}
createMarker(anchor: SimplifiedTrackPoint) {
let element = document.createElement('div');
element.className = `h-3 w-3 rounded-full bg-white border-2 border-black cursor-pointer`;
let marker = new mapboxgl.Marker({
draggable: true,
className: 'z-10',
element
}).setLngLat(anchor.point.getCoordinates());
Object.defineProperty(marker, '_simplified', {
value: anchor
});
anchor.marker = marker;
let lastDragEvent = 0;
marker.on('dragstart', (e) => {
lastDragEvent = Date.now();
this.map.getCanvas().style.cursor = 'grabbing';
element.classList.add('cursor-grabbing');
});
marker.on('dragend', () => {
lastDragEvent = Date.now();
this.map.getCanvas().style.cursor = '';
element.classList.remove('cursor-grabbing');
});
marker.on('dragend', this.moveAnchor.bind(this));
marker.getElement().addEventListener('click', (e) => {
if (Date.now() - lastDragEvent < 100) { // Prevent click event during drag
return;
}
marker.setPopup(this.popup);
marker.togglePopup();
e.stopPropagation();
let deleteThisAnchor = this.getDeleteAnchor(anchor);
this.popupElement.addEventListener('delete', deleteThisAnchor); // Register the delete event for this anchor
this.popup.once('close', () => {
this.popupElement.removeEventListener('delete', deleteThisAnchor);
});
});
this.markers.push(marker);
}
toggleMarkersForZoomLevelAndBounds() { // Show markers only if they are in the current zoom level and bounds
this.shownMarkers.splice(0, this.shownMarkers.length);
let zoom = this.map.getZoom();
this.markers.forEach((marker) => {
Object.defineProperty(marker, '_inZoom', {
value: marker._simplified.zoom <= zoom,
writable: true
});
if (marker._inZoom && this.map.getBounds().contains(marker.getLngLat())) {
marker.addTo(this.map);
this.shownMarkers.push(marker);
} else {
marker.remove();
}
});
}
showTemporaryAnchor(e: any) {
if (!this.temporaryAnchor.marker) {
return;
}
if (this.temporaryAnchorCloseToOtherAnchor(e)) {
return;
}
this.temporaryAnchor.point.setCoordinates({
lat: e.lngLat.lat,
lon: e.lngLat.lng
});
this.temporaryAnchor.marker.setLngLat(this.temporaryAnchor.point.getCoordinates()).addTo(this.map);
this.map.on('mousemove', this.hideTemporaryAnchorBinded);
}
hideTemporaryAnchor(e: any) {
if (!this.temporaryAnchor.marker) {
return;
}
if (this.temporaryAnchor.marker.getElement().classList.contains('cursor-grabbing')) { // Do not hide if it is being dragged, and stop listening for mousemove
this.map.off('mousemove', this.hideTemporaryAnchorBinded);
return;
}
if (e.point.dist(this.map.project(this.temporaryAnchor.point.getCoordinates())) > 20 || this.temporaryAnchorCloseToOtherAnchor(e)) { // Hide if too far from the layer
this.temporaryAnchor.marker.remove();
this.map.off('mousemove', this.hideTemporaryAnchorBinded);
return;
}
this.temporaryAnchor.marker.setLngLat(e.lngLat); // Update the position of the temporary anchor
}
temporaryAnchorCloseToOtherAnchor(e: any) {
for (let marker of this.shownMarkers) {
if (marker === this.temporaryAnchor.marker) {
continue;
}
if (e.point.dist(this.map.project(marker.getLngLat())) < 10) {
return true;
}
}
return false;
}
async moveAnchor(e: any) { // Move the anchor and update the route from and to the neighbouring anchors
let marker = e.target;
let anchor = marker._simplified;
if (marker._temporary) { // Temporary anchor, need to find the closest point of the segment and create an anchor for it
marker.remove();
anchor = this.getPermanentAnchor(anchor);
marker = anchor.marker;
}
let latlng = marker.getLngLat();
let coordinates = {
lat: latlng.lat,
lon: latlng.lng
};
let [previousAnchor, nextAnchor] = this.getNeighbouringAnchors(anchor);
let anchors = [];
let targetCoordinates = [];
if (previousAnchor !== null) {
anchors.push(previousAnchor);
targetCoordinates.push(previousAnchor.point.getCoordinates());
}
anchors.push(anchor);
targetCoordinates.push(coordinates);
if (nextAnchor !== null) {
anchors.push(nextAnchor);
targetCoordinates.push(nextAnchor.point.getCoordinates());
}
let success = await this.routeBetweenAnchors(anchors, targetCoordinates);
if (!success) { // Route failed, revert the anchor to the previous position
marker.setLngLat(anchor.point.getCoordinates());
}
}
getPermanentAnchor(anchor: SimplifiedTrackPoint) {
// Find the closest point closest to the temporary anchor
let minDistance = Number.MAX_VALUE;
let minPoint: TrackPoint | null = null;
for (let segment of get(this.file).getSegments()) {
for (let point of segment.trkpt) {
let dist = distance(point.getCoordinates(), anchor.point.getCoordinates());
if (dist < minDistance) {
minDistance = dist;
minPoint = point;
}
}
}
if (!minPoint) {
return anchor;
}
let segment = minPoint._data.segment;
let newAnchorIndex = segment._data.anchors.findIndex((a) => a.point._data.index >= minPoint._data.index);
if (segment._data.anchors[newAnchorIndex].point._data.index === minPoint._data.index) { // Anchor already exists for this point
return segment._data.anchors[newAnchorIndex];
}
let newAnchor = {
point: minPoint,
zoom: 0
};
this.createMarker(newAnchor);
let marker = this.markers.pop();
marker?.setLngLat(anchor.marker.getLngLat()).addTo(this.map);
segment._data.anchors.splice(newAnchorIndex, 0, newAnchor);
this.markers.splice(newAnchorIndex, 0, marker);
return newAnchor;
}
getDeleteAnchor(anchor: SimplifiedTrackPoint) {
return () => this.deleteAnchor(anchor);
}
async deleteAnchor(anchor: SimplifiedTrackPoint) { // Remove the anchor and route between the neighbouring anchors if they exist
let [previousAnchor, nextAnchor] = this.getNeighbouringAnchors(anchor);
if (previousAnchor === null) {
// remove trackpoints until nextAnchor
} else if (nextAnchor === null) {
// remove trackpoints from previousAnchor
} else {
// route between previousAnchor and nextAnchor
this.routeBetweenAnchors([previousAnchor, nextAnchor], [previousAnchor.point.getCoordinates(), nextAnchor.point.getCoordinates()]);
}
}
async appendAnchor(e: mapboxgl.MapMouseEvent) { // Add a new anchor to the end of the last segment
let segments = get(this.file).getSegments();
if (segments.length === 0) {
return;
}
let segment = segments[segments.length - 1];
let anchors = segment._data.anchors;
let lastAnchor = anchors[anchors.length - 1];
let newPoint = new TrackPoint({
attributes: {
lon: e.lngLat.lng,
lat: e.lngLat.lat
}
});
newPoint._data.index = segment.trkpt.length - 1; // Do as if the point was the last point in the segment
newPoint._data.segment = segment;
let newAnchor = {
point: newPoint,
zoom: 0
};
this.createMarker(newAnchor);
segment._data.anchors.push(newAnchor);
if (!lastAnchor) {
applyToFileElement(this.file, segment, (segment) => {
segment.replace(0, 0, [newPoint]);
}, true);
return;
}
let success = await this.routeBetweenAnchors([lastAnchor, newAnchor], [lastAnchor.point.getCoordinates(), newAnchor.point.getCoordinates()]);
if (!success) { // Route failed, remove the anchor
segment._data.anchors.pop();
this.markers.pop()?.remove();
}
}
getNeighbouringAnchors(anchor: SimplifiedTrackPoint): [SimplifiedTrackPoint | null, SimplifiedTrackPoint | null] {
let previousAnchor: SimplifiedTrackPoint | null = null;
let nextAnchor: SimplifiedTrackPoint | null = null;
let segment = anchor.point._data.segment;
let anchors = segment._data.anchors;
for (let i = 0; i < anchors.length; i++) {
if (anchors[i].point._data.index < anchor.point._data.index &&
anchors[i].point._data.segment === anchor.point._data.segment &&
anchors[i].marker._inZoom) {
if (!previousAnchor || anchors[i].point._data.index > previousAnchor.point._data.index) {
previousAnchor = anchors[i];
}
} else if (anchors[i].point._data.index > anchor.point._data.index &&
anchors[i].point._data.segment === anchor.point._data.segment &&
anchors[i].marker._inZoom) {
if (!nextAnchor || anchors[i].point._data.index < nextAnchor.point._data.index) {
nextAnchor = anchors[i];
}
}
}
return [previousAnchor, nextAnchor];
}
async routeBetweenAnchors(anchors: SimplifiedTrackPoint[], targetCoordinates: Coordinates[]): Promise<boolean> {
if (anchors.length === 1) {
anchors[0].point.setCoordinates(targetCoordinates[0]);
return true;
}
let segment = anchors[0].point._data.segment;
let response: TrackPoint[];
try {
response = await route(targetCoordinates);
} catch (e) {
if (e.message.includes('from-position not mapped in existing datafile')) {
toast.error(get(_)("toolbar.routing.error.from"));
} else if (e.message.includes('via1-position not mapped in existing datafile')) {
toast.error(get(_)("toolbar.routing.error.via"));
} else if (e.message.includes('to-position not mapped in existing datafile')) {
toast.error(get(_)("toolbar.routing.error.to"));
} else if (e.message.includes('Time-out')) {
toast.error(get(_)("toolbar.routing.error.timeout"));
} else {
toast.error(e.message);
}
return false;
}
let start = anchors[0].point._data.index + 1;
let end = anchors[anchors.length - 1].point._data.index - 1;
if (anchors[0].point._data.index === 0) { // First anchor is the first point of the segment
anchors[0].point = response[0]; // Update the first anchor in case it was not on a road
start--; // Remove the original first point
}
if (anchors[anchors.length - 1].point._data.index === anchors[anchors.length - 1].point._data.segment.trkpt.length - 1) { // Last anchor is the last point of the segment
anchors[anchors.length - 1].point = response[response.length - 1]; // Update the last anchor in case it was not on a road
end++; // Remove the original last point
}
for (let i = 1; i < anchors.length - 1; i++) {
// Find the closest point to the intermediate anchor
// and transfer the marker to that point
let minDistance = Number.MAX_VALUE;
let minIndex = 0;
for (let j = 1; j < response.length - 1; j++) {
let dist = distance(response[j].getCoordinates(), targetCoordinates[i]);
if (dist < minDistance) {
minDistance = dist;
minIndex = j;
}
}
anchors[i].point = response[minIndex];
}
anchors.forEach((anchor) => {
anchor.zoom = 0; // Make these anchors permanent
anchor.marker.setLngLat(anchor.point.getCoordinates()); // Update the marker position if needed
});
applyToFileElement(this.file, segment, (segment) => {
segment.replace(start, end, response);
}, true);
return true;
}
}

View File

@@ -0,0 +1,119 @@
import type { Coordinates, TrackPoint, TrackSegment } from "gpx";
export type SimplifiedTrackPoint = { point: TrackPoint, distance?: number, zoom?: number, marker?: mapboxgl.Marker };
const earthRadius = 6371008.8;
export 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))));
}
export function computeAnchorPoints(segment: TrackSegment) {
let points = segment.trkpt;
let anchors = ramerDouglasPeucker(points);
anchors.forEach((point) => {
point.zoom = getZoomLevelForDistance(point.point.getLatitude(), point.distance);
});
segment._data['anchors'] = anchors;
}
export function ramerDouglasPeucker(points: TrackPoint[], epsilon: number = 50, start: number = 0, end: number = points.length - 1): SimplifiedTrackPoint[] {
if (points.length == 0) {
return [];
} else if (points.length == 1) {
return [{
point: points[0]
}];
}
let simplified = [{
point: points[start]
}];
ramerDouglasPeuckerRecursive(points, epsilon, start, end, simplified);
simplified.push({
point: points[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], distance: largest.distance });
ramerDouglasPeuckerRecursive(points, epsilon, largest.index, end, simplified);
}
}
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));
}