Skip to content

Commit

Permalink
[svelte] Use a default location for nearest stops
Browse files Browse the repository at this point in the history
  • Loading branch information
matteocontrini committed Jun 24, 2024
1 parent f3a9131 commit 0df2696
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
16 changes: 16 additions & 0 deletions src/lib/location-helpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,20 @@
import type { Coordinates } from '$lib/Coordinates';
import type { StopGroup } from '$lib/StopGroup';

export function computeDistances(stops: StopGroup[], userCoordinates: GeolocationCoordinates | null = null) {
const distances = new Map<string, number>();

// Default to Piazza Dante Trento
if (!userCoordinates) {
userCoordinates = { latitude: 46.071756, longitude: 11.119511 } as GeolocationCoordinates;
}

for (const stop of stops) {
distances.set(stop.code, distance(userCoordinates, stop.coordinates));
}

return distances;
}

export function distance(userCoordinates: GeolocationCoordinates | null, stopCoordinates: Coordinates) {
if (userCoordinates == null) {
Expand Down
17 changes: 8 additions & 9 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@
import ModesSwitch from '$lib/components/ModesSwitch.svelte';
import TabButton from '$lib/components/TabButton.svelte';
import { getContext, onMount } from 'svelte';
import { distance, getCurrentPosition, handleGeolocationError, isGeolocationGranted } from '$lib/location-helpers';
import {
computeDistances,
getCurrentPosition,
handleGeolocationError,
isGeolocationGranted
} from '$lib/location-helpers';
import { type FavoritesStore } from '$lib/stores/stops-favorites';
import { getDefaultTab, setDefaultTab, type Tab } from '$lib/storage/stops-default-tab';
Expand All @@ -18,7 +23,7 @@
$: escapedSearchTerm = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
let showGeolocationButton = false;
let distances = new Map<string, number>();
let distances = computeDistances(data.stops);
const favorites: FavoritesStore = getContext('favorites');
Expand Down Expand Up @@ -54,13 +59,7 @@
async function updatePosition() {
try {
const position = await getCurrentPosition();
// Recalculate distances
for (let stop of data.stops) {
distances.set(stop.code, distance(position.coords, stop.coordinates));
}
distances = distances; // trigger re-render
distances = computeDistances(data.stops, position.coords);
showGeolocationButton = false;
} catch (err) {
handleGeolocationError(err);
Expand Down

0 comments on commit 0df2696

Please sign in to comment.