Skip to content

Commit

Permalink
Run Prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
haysmike committed Oct 22, 2024
1 parent 36904ae commit e3d8d06
Show file tree
Hide file tree
Showing 10 changed files with 184 additions and 87 deletions.
46 changes: 33 additions & 13 deletions web/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
Expand All @@ -12,7 +12,7 @@
<button id="simulate">Simulate Navigation</button>
</p>

<p style="margin-top: 0;">
<p style="margin-top: 0">
<input type="checkbox" id="voiceGuidance" />
<label for="voiceGuidance">Enable voice guidance (sound on)</label>
</p>
Expand All @@ -30,8 +30,12 @@
></ferrostar-map>

<script type="module">
import { FerrostarMap, SimulatedLocationProvider, BrowserLocationProvider } from "@stadiamaps/ferrostar-webcomponents";
import {MapLibreSearchControl} from "@stadiamaps/maplibre-search-box";
import {
FerrostarMap,
SimulatedLocationProvider,
BrowserLocationProvider,
} from "@stadiamaps/ferrostar-webcomponents";
import { MapLibreSearchControl } from "@stadiamaps/maplibre-search-box";
import searchBoxStyle from "@stadiamaps/maplibre-search-box/dist/style.css?inline";

// TODO: type + use TypeScript enum
Expand All @@ -48,7 +52,7 @@
maxAcceptableDeviation: 10.0,
},
},
snappedLocationCourseFiltering: "Raw"
snappedLocationCourseFiltering: "Raw",
};

async function onload() {
Expand All @@ -59,17 +63,26 @@
const searchBox = new MapLibreSearchControl({
onResultSelected: async (feature) => {
const coordinates = feature.geometry.coordinates;
const waypoints = [{ coordinate: { lat: coordinates[1], lng: coordinates[0] }, kind: "Break" }];
const waypoints = [
{
coordinate: { lat: coordinates[1], lng: coordinates[0] },
kind: "Break",
},
];

// FIXME: This is a hack basically to support the demo page that should go away.
if (!ferrostar.locationProvider || ferrostar.locationProvider instanceof SimulatedLocationProvider) {
if (
!ferrostar.locationProvider ||
ferrostar.locationProvider instanceof SimulatedLocationProvider
) {
ferrostar.locationProvider = new BrowserLocationProvider();
}

// Fetch the user's current location.
// If we have a cached one that's no older than 30 seconds,
// skip waiting for an update and use the slightly stale location.
const location = await ferrostar.locationProvider.getCurrentLocation(30_000);
const location =
await ferrostar.locationProvider.getCurrentLocation(30_000);

// Use the acquired user location to request the route
const routes = await ferrostar.getRoutes(location, waypoints);
Expand All @@ -94,9 +107,11 @@
},
});

ferrostar.center = {lng: -122.42, lat: 37.81};
ferrostar.center = { lng: -122.42, lat: 37.81 };
ferrostar.zoom = 18;
ferrostar.options = {costing_options: { bicycle: { use_roads: 0.2 } } };
ferrostar.options = {
costing_options: { bicycle: { use_roads: 0.2 } },
};
ferrostar.customStyles = searchBoxStyle;
ferrostar.geolocateOnLoad = false;

Expand All @@ -123,10 +138,15 @@
speed: null,
};

const simulatedWaypoints = [{ coordinate: { lat: 37.807587, lng: -122.428411 }, kind: "Break" }];
const simulatedWaypoints = [
{ coordinate: { lat: 37.807587, lng: -122.428411 }, kind: "Break" },
];

// Request the route
const routes = await ferrostar.getRoutes(initialSimulatedLocation, simulatedWaypoints);
const routes = await ferrostar.getRoutes(
initialSimulatedLocation,
simulatedWaypoints,
);
const route = routes[0];

// Set the simulated location provider
Expand All @@ -147,7 +167,7 @@
}

// Initialize Ferrostar and the control buttons
if ( document.readyState === "loading" ) {
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", onload);
} else {
onload();
Expand Down
4 changes: 2 additions & 2 deletions web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@
"prettier": "^3.3.3",
"typescript": "^5.2.2",
"vite": "^5.4.1",
"vitest": "^2.0.5",
"vite-plugin-top-level-await": "^1.4.4",
"vite-plugin-wasm": "^3.3.0",
"vite-plugin-top-level-await": "^1.4.4"
"vitest": "^2.0.5"
},
"keywords": [
"navigation",
Expand Down
24 changes: 18 additions & 6 deletions web/src/arrival-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { LitElement, css, html } from "lit";
import { customElement, property } from "lit/decorators.js";

function roundToNearest(value: number, unit: number): number {
return Math.round(value / unit) * unit
return Math.round(value / unit) * unit;
}

@customElement("arrival-view")
Expand Down Expand Up @@ -50,7 +50,7 @@ export class ArrivalView extends LitElement {
value = roundToNearest(value, 0.1);
}

return `${value.toLocaleString()}km`
return `${value.toLocaleString()}km`;
} else {
let value;
if (meters > 100) {
Expand All @@ -61,7 +61,7 @@ export class ArrivalView extends LitElement {
value = roundToNearest(meters, 5);
}

return `${value.toLocaleString()}m`
return `${value.toLocaleString()}m`;
}
}

Expand All @@ -74,9 +74,21 @@ export class ArrivalView extends LitElement {
if (this.tripState?.Navigating) {
return html`
<div class="arrival-view-card">
<p class="arrival-text">${this.getArrivalTime(this.tripState.Navigating.progress.durationRemaining)}</p>
<p class="arrival-text">${this.getDurationRemaining(this.tripState.Navigating.progress.durationRemaining)}</p>
<p class="arrival-text">${this.getDistanceRemaining(this.tripState.Navigating.progress.distanceRemaining)}</p>
<p class="arrival-text">
${this.getArrivalTime(
this.tripState.Navigating.progress.durationRemaining,
)}
</p>
<p class="arrival-text">
${this.getDurationRemaining(
this.tripState.Navigating.progress.durationRemaining,
)}
</p>
<p class="arrival-text">
${this.getDistanceRemaining(
this.tripState.Navigating.progress.distanceRemaining,
)}
</p>
</div>
`;
}
Expand Down
104 changes: 72 additions & 32 deletions web/src/ferrostar-map.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import {css, html, LitElement, PropertyValues, unsafeCSS} from "lit";
import {customElement, property, state} from "lit/decorators.js";
import { css, html, LitElement, PropertyValues, unsafeCSS } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import maplibregl, {
GeolocateControl,
LngLat,
LngLatLike,
Map
Map,
} from "maplibre-gl";
import maplibreglStyles from "maplibre-gl/dist/maplibre-gl.css?inline";
import {
NavigationController,
RouteAdapter,
TripState
TripState,
} from "@stadiamaps/ferrostar";
import "./instructions-view";
import "./arrival-view";
import {SimulatedLocationProvider} from "./location";
import { SimulatedLocationProvider } from "./location";
import CloseSvg from "./assets/directions/close.svg";

/**
Expand Down Expand Up @@ -133,7 +133,9 @@ export class FerrostarMap extends LitElement {
border: none;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
cursor: pointer;
transition: background-color 0.3s, filter 0.3s;
transition:
background-color 0.3s,
filter 0.3s;
}
#stop-button .icon {
Expand Down Expand Up @@ -162,49 +164,54 @@ export class FerrostarMap extends LitElement {
}
if (this.map) {
if (changedProperties.has("styleUrl")) {
this.map.setStyle(this.styleUrl)
this.map.setStyle(this.styleUrl);
}
if (changedProperties.has("center")) {
if (changedProperties.get("center") === null && this.center !== null) {
this.map.jumpTo({center: this.center})
this.map.jumpTo({ center: this.center });
} else if (this.center !== null) {
if (this.map.getCenter().distanceTo(LngLat.convert(this.center)) > 500_000) {
this.map.jumpTo({center: this.center});
if (
this.map.getCenter().distanceTo(LngLat.convert(this.center)) >
500_000
) {
this.map.jumpTo({ center: this.center });
} else {
this.map.flyTo({center: this.center});
this.map.flyTo({ center: this.center });
}
}
}
if (changedProperties.has("pitch")) {
this.map.setPitch(this.pitch)
this.map.setPitch(this.pitch);
}
if (changedProperties.has("zoom")) {
this.map.setZoom(this.zoom)
this.map.setZoom(this.zoom);
}
}
}

firstUpdated() {
this.map = new maplibregl.Map({
container: this.shadowRoot!.getElementById("map")!,
style: this.styleUrl ? this.styleUrl : "https://demotiles.maplibre.org/style.json",
style: this.styleUrl
? this.styleUrl
: "https://demotiles.maplibre.org/style.json",
center: this.center ?? [0, 0],
pitch: this.pitch,
bearing: 0,
zoom: this.zoom,
attributionControl: {compact: true}
attributionControl: { compact: true },
});

this.geolocateControl = new GeolocateControl({
positionOptions: {
enableHighAccuracy: true
enableHighAccuracy: true,
},
trackUserLocation: true
trackUserLocation: true,
});

this.map.addControl(this.geolocateControl);

this.map.on('load', (e) => {
this.map.on("load", (e) => {
if (this.geolocateOnLoad) {
this.geolocateControl?.trigger();
}
Expand All @@ -219,10 +226,17 @@ export class FerrostarMap extends LitElement {
async getRoutes(initialLocation: any, waypoints: any) {
// Initialize the route adapter
// (NOTE: currently only supports Valhalla, but working toward expansion)
this.routeAdapter = new RouteAdapter(this.valhallaEndpointUrl, this.profile, JSON.stringify(this.options));
this.routeAdapter = new RouteAdapter(
this.valhallaEndpointUrl,
this.profile,
JSON.stringify(this.options),
);

// Generate the request body
const routeRequest = this.routeAdapter.generateRequest(initialLocation, waypoints);
const routeRequest = this.routeAdapter.generateRequest(
initialLocation,
waypoints,
);
const method = routeRequest.get("method");
let url = new URL(routeRequest.get("url"));
const body = routeRequest.get("body");
Expand Down Expand Up @@ -259,7 +273,8 @@ export class FerrostarMap extends LitElement {
speed: null,
};

this._tripState = this.navigationController.getInitialState(startingLocation);
this._tripState =
this.navigationController.getInitialState(startingLocation);

// Update the UI with the initial trip state
this.clearMap();
Expand All @@ -271,7 +286,9 @@ export class FerrostarMap extends LitElement {
properties: {},
geometry: {
type: "LineString",
coordinates: route.geometry.map((point: { lat: number; lng: number }) => [point.lng, point.lat]),
coordinates: route.geometry.map(
(point: { lat: number; lng: number }) => [point.lng, point.lat],
),
},
},
});
Expand All @@ -294,10 +311,10 @@ export class FerrostarMap extends LitElement {

if (this.locationProvider instanceof SimulatedLocationProvider) {
this.simulatedLocationMarker = new maplibregl.Marker({
color: 'green'
color: "green",
})
.setLngLat(route.geometry[0])
.addTo(this.map!);
.setLngLat(route.geometry[0])
.addTo(this.map!);
}
}

Expand All @@ -318,10 +335,15 @@ export class FerrostarMap extends LitElement {
return;
}
// Update the trip state with the new location
this._tripState = this.navigationController!.updateUserLocation(this.locationProvider.lastLocation, this._tripState);
this._tripState = this.navigationController!.updateUserLocation(
this.locationProvider.lastLocation,
this._tripState,
);

// Update the simulated location marker if needed
this.simulatedLocationMarker?.setLngLat(this.locationProvider.lastLocation.coordinates);
this.simulatedLocationMarker?.setLngLat(
this.locationProvider.lastLocation.coordinates,
);

// Center the map on the user's location
this.map?.easeTo({
Expand All @@ -331,11 +353,25 @@ export class FerrostarMap extends LitElement {

// Speak the next instruction if voice guidance is enabled
const tripState = this._tripState;
if (this.useVoiceGuidance && tripState != null && typeof tripState === 'object') {
if ("Navigating" in tripState && tripState.Navigating?.spokenInstruction && tripState.Navigating?.spokenInstruction.utteranceId !== this.lastSpokenUtteranceId) {
this.lastSpokenUtteranceId = tripState.Navigating?.spokenInstruction.utteranceId;
if (
this.useVoiceGuidance &&
tripState != null &&
typeof tripState === "object"
) {
if (
"Navigating" in tripState &&
tripState.Navigating?.spokenInstruction &&
tripState.Navigating?.spokenInstruction.utteranceId !==
this.lastSpokenUtteranceId
) {
this.lastSpokenUtteranceId =
tripState.Navigating?.spokenInstruction.utteranceId;
window.speechSynthesis.cancel();
window.speechSynthesis.speak(new SpeechSynthesisUtterance(tripState.Navigating?.spokenInstruction.text));
window.speechSynthesis.speak(
new SpeechSynthesisUtterance(
tripState.Navigating?.spokenInstruction.text,
),
);
}
}
}
Expand All @@ -355,7 +391,11 @@ export class FerrostarMap extends LitElement {
<instructions-view .tripState=${this._tripState}></instructions-view>
<div id="bottom-component">
<arrival-view .tripState=${this._tripState}></arrival-view>
<button id="stop-button" @click=${this.stopNavigation} ?hidden=${!this._tripState}>
<button
id="stop-button"
@click=${this.stopNavigation}
?hidden=${!this._tripState}
>
<img src=${CloseSvg} alt="Stop navigation" class="icon" />
</button>
</div>
Expand Down
Loading

0 comments on commit e3d8d06

Please sign in to comment.