Skip to content

Colota - Android GPS Location tracker

Add speed-colored track, point popups, and locale-aware speed display

Max Dietrich8fae2ff4d223
diff --git a/apps/mobile/src/components/features/inspector/TrackMap.tsx b/apps/mobile/src/components/features/inspector/TrackMap.tsx
index 1cd7055c..d1be10dd 100644
--- a/apps/mobile/src/components/features/inspector/TrackMap.tsx
+++ b/apps/mobile/src/components/features/inspector/TrackMap.tsx
@@ -10,7 +10,8 @@ import { MapPin } from "lucide-react-native"
import { ThemeColors } from "../../../types/global"
import { fonts } from "../../../styles/typography"
import { MapCenterButton } from "../map/MapCenterButton"
-import { mapStyles } from "../map/mapHtml"
+import { mapStyles, mapSpeedColorHelpers } from "../map/mapHtml"
+import { getSpeedUnit } from "../../../utils/geo"
interface TrackLocation {
latitude: number
@@ -30,9 +31,16 @@ interface Props {
export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {
const webviewRef = useRef<WebView>(null)
+ const isMounted = useRef(true)
const [mapReady, setMapReady] = useState(false)
const [isCentered, setIsCentered] = useState(true)
+ useEffect(() => {
+ return () => {
+ isMounted.current = false
+ }
+ }, [])
+
// Send locations to the map when they change or map becomes ready
useEffect(() => {
if (webviewRef.current && mapReady && locations.length > 0) {
@@ -41,7 +49,11 @@ export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {
action: "update_track",
locations: locations.map((l) => ({
lon: l.longitude,
- lat: l.latitude
+ lat: l.latitude,
+ speed: l.speed ?? 0,
+ timestamp: l.timestamp ?? 0,
+ accuracy: l.accuracy ?? 0,
+ altitude: l.altitude ?? 0
}))
})
)
@@ -66,6 +78,11 @@ export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {
}, [])
const html = useMemo(() => {
+ const { factor: speedFactor, unit: speedUnit } = getSpeedUnit()
+ const slowLabel = `&lt; ${Math.round(2 * speedFactor)} ${speedUnit}`
+ const midLabel = `${Math.round(2 * speedFactor)}–${Math.round(8 * speedFactor)} ${speedUnit}`
+ const fastLabel = `&gt; ${Math.round(8 * speedFactor)} ${speedUnit}`
+
return `
<!DOCTYPE html>
<html>
@@ -76,25 +93,53 @@ export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {
</head>
<body>
<div id="map"></div>
+ <div id="popup" class="ol-popup">
+ <button id="popup-closer" class="ol-popup-closer">&times;</button>
+ <div id="popup-content" class="ol-popup-content"></div>
+ </div>
+ <div class="speed-legend">
+ <div class="speed-legend-item">
+ <div class="speed-legend-dot" style="background:${colors.success}"></div>
+ <span class="speed-legend-label">${slowLabel}</span>
+ </div>
+ <div class="speed-legend-item">
+ <div class="speed-legend-dot" style="background:${colors.warning}"></div>
+ <span class="speed-legend-label">${midLabel}</span>
+ </div>
+ <div class="speed-legend-item">
+ <div class="speed-legend-dot" style="background:${colors.error}"></div>
+ <span class="speed-legend-label">${fastLabel}</span>
+ </div>
+ </div>
<script src="openlayers/ol.js"></script>
<script>
- const trackSource = new ol.source.Vector();
- const markerSource = new ol.source.Vector();
- const highlightSource = new ol.source.Vector();
+ ${mapSpeedColorHelpers(colors)}
+
+ var SPEED_FACTOR = ${speedFactor};
+ var SPEED_UNIT = "${speedUnit}";
+
+ var trackSource = new ol.source.Vector();
+ var pointSource = new ol.source.Vector();
+ var markerSource = new ol.source.Vector();
+ var highlightSource = new ol.source.Vector();
- const map = new ol.Map({
+ var popupEl = document.getElementById("popup");
+ var popupContent = document.getElementById("popup-content");
+ var popupCloser = document.getElementById("popup-closer");
+
+ var popupOverlay = new ol.Overlay({
+ element: popupEl,
+ autoPan: true,
+ autoPanAnimation: { duration: 250 }
+ });
+
+ var map = new ol.Map({
target: "map",
+ overlays: [popupOverlay],
layers: [
new ol.layer.Tile({ source: new ol.source.OSM() }),
- new ol.layer.Vector({
- source: trackSource,
- style: new ol.style.Style({
- stroke: new ol.style.Stroke({
- color: "${colors.primary}",
- width: 3
- })
- })
- }),
+ new ol.layer.Vector({ source: trackSource }),
+ new ol.layer.Vector({ source: pointSource }),
new ol.layer.Vector({ source: markerSource }),
new ol.layer.Vector({ source: highlightSource })
],
@@ -104,37 +149,77 @@ export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {
})
});
- let currentExtent = null;
+ popupCloser.onclick = function() {
+ popupOverlay.setPosition(undefined);
+ return false;
+ };
+
+ var currentExtent = null;
function updateTrack(locations) {
trackSource.clear();
+ pointSource.clear();
markerSource.clear();
+ popupOverlay.setPosition(undefined);
if (!locations || locations.length === 0) return;
- // Build polyline
- const coords = locations.map(l => ol.proj.fromLonLat([l.lon, l.lat]));
- const line = new ol.geom.LineString(coords);
- trackSource.addFeature(new ol.Feature(line));
+ var allCoords = locations.map(function(l) {
+ return ol.proj.fromLonLat([l.lon, l.lat]);
+ });
+
+ // Speed-colored segments
+ for (var i = 1; i < locations.length; i++) {
+ var avgSpeed = (locations[i - 1].speed + locations[i].speed) / 2;
+ var segCoords = [allCoords[i - 1], allCoords[i]];
+ var seg = new ol.Feature(new ol.geom.LineString(segCoords));
+ seg.setStyle(new ol.style.Style({
+ stroke: new ol.style.Stroke({
+ color: getSpeedColor(avgSpeed),
+ width: 3
+ })
+ }));
+ trackSource.addFeature(seg);
+ }
+
+ // Point markers with stored properties
+ for (var j = 0; j < locations.length; j++) {
+ var loc = locations[j];
+ var pt = new ol.Feature(new ol.geom.Point(allCoords[j]));
+ pt.set("_speed", loc.speed);
+ pt.set("_timestamp", loc.timestamp);
+ pt.set("_accuracy", loc.accuracy);
+ pt.set("_altitude", loc.altitude);
+ pt.set("_type", "track_point");
+ var ptColor = getSpeedColor(loc.speed);
+ pt.setStyle(new ol.style.Style({
+ image: new ol.style.Circle({
+ radius: 4,
+ fill: new ol.style.Fill({ color: ptColor + "66" }),
+ stroke: new ol.style.Stroke({ color: ptColor, width: 1.5 })
+ })
+ }));
+ pointSource.addFeature(pt);
+ }
// Start marker (green)
- const startFeature = new ol.Feature(new ol.geom.Point(coords[0]));
+ var startFeature = new ol.Feature(new ol.geom.Point(allCoords[0]));
startFeature.setStyle(new ol.style.Style({
image: new ol.style.Circle({
radius: 8,
- fill: new ol.style.Fill({ color: "#22c55e" }),
+ fill: new ol.style.Fill({ color: SPEED_COLORS.slow }),
stroke: new ol.style.Stroke({ color: "#fff", width: 2 })
})
}));
markerSource.addFeature(startFeature);
- // End marker (red) — only if more than one point
- if (coords.length > 1) {
- const endFeature = new ol.Feature(new ol.geom.Point(coords[coords.length - 1]));
+ // End marker (red)
+ if (allCoords.length > 1) {
+ var endFeature = new ol.Feature(new ol.geom.Point(allCoords[allCoords.length - 1]));
endFeature.setStyle(new ol.style.Style({
image: new ol.style.Circle({
radius: 8,
- fill: new ol.style.Fill({ color: "#ef4444" }),
+ fill: new ol.style.Fill({ color: SPEED_COLORS.fast }),
stroke: new ol.style.Stroke({ color: "#fff", width: 2 })
})
}));
@@ -142,7 +227,8 @@ export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {
}
// Fit map to track extent
- currentExtent = line.getExtent();
+ var fullLine = new ol.geom.LineString(allCoords);
+ currentExtent = fullLine.getExtent();
fitTrack();
}
@@ -159,10 +245,9 @@ export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {
function zoomToPoint(lon, lat) {
highlightSource.clear();
- const pos = ol.proj.fromLonLat([lon, lat]);
+ var pos = ol.proj.fromLonLat([lon, lat]);
- // Add highlight marker
- const highlight = new ol.Feature(new ol.geom.Point(pos));
+ var highlight = new ol.Feature(new ol.geom.Point(pos));
highlight.setStyle(new ol.style.Style({
image: new ol.style.Circle({
radius: 12,
@@ -179,8 +264,40 @@ export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {
});
}
+ // Popup on point tap
+ map.on("singleclick", function(evt) {
+ var found = false;
+ map.forEachFeatureAtPixel(evt.pixel, function(feature) {
+ if (found) return;
+ if (feature.get("_type") !== "track_point") return;
+ found = true;
+
+ var ts = feature.get("_timestamp");
+ var speed = feature.get("_speed");
+ var accuracy = feature.get("_accuracy");
+ var altitude = feature.get("_altitude");
+
+ var timeStr = ts ? new Date(ts * 1000).toLocaleTimeString() : "—";
+ var speedStr = speed != null ? (speed * SPEED_FACTOR).toFixed(1) + " " + SPEED_UNIT : "—";
+ var accStr = accuracy != null ? "\\u00B1" + accuracy.toFixed(0) + "m" : "—";
+ var altStr = altitude != null ? altitude.toFixed(0) + "m" : "—";
+
+ popupContent.innerHTML =
+ '<div class="popup-time">' + timeStr + '</div>' +
+ '<div class="popup-row"><span class="popup-label">Speed</span><span class="popup-value">' + speedStr + '</span></div>' +
+ '<div class="popup-row"><span class="popup-label">Accuracy</span><span class="popup-value">' + accStr + '</span></div>' +
+ '<div class="popup-row"><span class="popup-label">Altitude</span><span class="popup-value">' + altStr + '</span></div>';
+
+ popupOverlay.setPosition(feature.getGeometry().getCoordinates());
+ }, { hitTolerance: 10 });
+
+ if (!found) {
+ popupOverlay.setPosition(undefined);
+ }
+ });
+
function handleInternalMessage(e) {
- let data;
+ var data;
try {
data = JSON.parse(e.data);
} catch(err) {
@@ -203,7 +320,7 @@ export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {
window.addEventListener("message", handleInternalMessage);
document.addEventListener("message", handleInternalMessage);
- map.on("moveend", () => {
+ map.on("moveend", function() {
var centered = true;
if (currentExtent) {
var viewExtent = map.getView().calculateExtent(map.getSize());
@@ -246,6 +363,7 @@ export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {
scrollEnabled={false}
startInLoadingState={false}
onMessage={(event) => {
+ if (!isMounted.current) return
try {
const data = JSON.parse(event.nativeEvent.data)
@@ -259,7 +377,11 @@ export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {
action: "update_track",
locations: locations.map((l) => ({
lon: l.longitude,
- lat: l.latitude
+ lat: l.latitude,
+ speed: l.speed ?? 0,
+ timestamp: l.timestamp ?? 0,
+ accuracy: l.accuracy ?? 0,
+ altitude: l.altitude ?? 0
}))
})
)
diff --git a/apps/mobile/src/components/features/map/mapHtml.ts b/apps/mobile/src/components/features/map/mapHtml.ts
index d14f55b3..897a7acd 100644
--- a/apps/mobile/src/components/features/map/mapHtml.ts
+++ b/apps/mobile/src/components/features/map/mapHtml.ts
@@ -137,10 +137,155 @@ export function mapStyles(colors: ThemeColors, isDark: boolean): string {
}
}
+ .ol-popup {
+ position: absolute;
+ background: ${colors.card};
+ border: 1px solid ${colors.border};
+ border-radius: ${colors.borderRadius}px;
+ padding: 12px 14px;
+ min-width: 160px;
+ max-width: 220px;
+ box-shadow: 0 4px 12px rgba(0,0,0,0.2);
+ bottom: 14px;
+ left: -110px;
+ width: 220px;
+ }
+
+ .ol-popup:after {
+ content: '';
+ position: absolute;
+ bottom: -8px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 0;
+ height: 0;
+ border-left: 8px solid transparent;
+ border-right: 8px solid transparent;
+ border-top: 8px solid ${colors.card};
+ }
+
+ .ol-popup-closer {
+ position: absolute;
+ top: 4px;
+ right: 8px;
+ font-size: 18px;
+ color: ${colors.textSecondary};
+ cursor: pointer;
+ background: none;
+ border: none;
+ padding: 0;
+ line-height: 1;
+ }
+
+ .ol-popup-content {
+ font-family: -apple-system, sans-serif;
+ font-size: 12px;
+ color: ${colors.text};
+ line-height: 1.6;
+ }
+
+ .ol-popup-content .popup-time {
+ font-weight: 600;
+ font-size: 13px;
+ margin-bottom: 4px;
+ }
+
+ .ol-popup-content .popup-row {
+ display: flex;
+ justify-content: space-between;
+ }
+
+ .ol-popup-content .popup-label {
+ color: ${colors.textSecondary};
+ font-size: 11px;
+ text-transform: uppercase;
+ font-weight: 600;
+ }
+
+ .ol-popup-content .popup-value {
+ font-weight: 500;
+ }
+
+ .speed-legend {
+ position: absolute;
+ bottom: 10px;
+ left: 10px;
+ background: ${colors.card};
+ border: 1px solid ${colors.border};
+ border-radius: ${colors.borderRadius}px;
+ padding: 8px 10px;
+ font-family: -apple-system, sans-serif;
+ font-size: 11px;
+ color: ${colors.text};
+ box-shadow: 0 2px 8px rgba(0,0,0,0.15);
+ z-index: 100;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+
+ .speed-legend-item {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+
+ .speed-legend-dot {
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ flex-shrink: 0;
+ }
+
+ .speed-legend-label {
+ color: ${colors.textSecondary};
+ font-weight: 500;
+ }
+
${isDark ? ".ol-layer canvas { filter: brightness(0.6) contrast(1.2) saturate(0.8); }" : ""}
`
}
+/** JS helpers for speed-colored track rendering.
+ * Provides SPEED_COLORS, parseHex, lerpColor, and getSpeedColor. */
+export function mapSpeedColorHelpers(colors: ThemeColors): string {
+ return `
+ var SPEED_COLORS = {
+ slow: "${colors.success}",
+ medium: "${colors.warning}",
+ fast: "${colors.error}"
+ };
+
+ function parseHex(hex) {
+ hex = hex.replace("#", "");
+ return [
+ parseInt(hex.substring(0, 2), 16),
+ parseInt(hex.substring(2, 4), 16),
+ parseInt(hex.substring(4, 6), 16)
+ ];
+ }
+
+ function lerpColor(c1, c2, t) {
+ var a = parseHex(c1), b = parseHex(c2);
+ var r = Math.round(a[0] + (b[0] - a[0]) * t);
+ var g = Math.round(a[1] + (b[1] - a[1]) * t);
+ var bl = Math.round(a[2] + (b[2] - a[2]) * t);
+ return "rgb(" + r + "," + g + "," + bl + ")";
+ }
+
+ function getSpeedColor(speed) {
+ if (speed <= 2) return SPEED_COLORS.slow;
+ if (speed >= 8) return SPEED_COLORS.fast;
+ if (speed <= 5) {
+ var t = (speed - 2) / 3;
+ return lerpColor(SPEED_COLORS.slow, SPEED_COLORS.medium, t);
+ }
+ var t2 = (speed - 5) / 3;
+ return lerpColor(SPEED_COLORS.medium, SPEED_COLORS.fast, t2);
+ }
+ `
+}
+
/** JS helpers for maps with a user-position marker overlay.
* Expects `map` and `markerOverlay` to exist in scope. */
export function mapMarkerHelpers(): string {
diff --git a/apps/mobile/src/utils/__tests__/geo.test.ts b/apps/mobile/src/utils/__tests__/geo.test.ts
index 9940805e..43587ec3 100644
--- a/apps/mobile/src/utils/__tests__/geo.test.ts
+++ b/apps/mobile/src/utils/__tests__/geo.test.ts
@@ -1,4 +1,4 @@
-import { computeTotalDistance, formatDistance } from "../geo"
+import { computeTotalDistance, formatDistance, formatSpeed } from "../geo"
describe("computeTotalDistance", () => {
it("returns 0 for empty array", () => {
@@ -93,3 +93,50 @@ describe("formatDistance", () => {
expect(formatDistance(5000)).toBe("5.0 km")
})
})
+
+describe("formatSpeed", () => {
+ let originalNumberFormat: typeof Intl.NumberFormat
+
+ beforeEach(() => {
+ originalNumberFormat = Intl.NumberFormat
+ })
+
+ afterEach(() => {
+ // @ts-ignore – restore original
+ Intl.NumberFormat = originalNumberFormat
+ })
+
+ it("formats as km/h for non-US locales", () => {
+ // @ts-ignore – mock Intl
+ Intl.NumberFormat = jest.fn(() => ({
+ resolvedOptions: () => ({ locale: "de-DE" })
+ }))
+ // 2 m/s = 7.2 km/h
+ expect(formatSpeed(2)).toBe("7.2 km/h")
+ })
+
+ it("formats as mph for en-US locale", () => {
+ // @ts-ignore – mock Intl
+ Intl.NumberFormat = jest.fn(() => ({
+ resolvedOptions: () => ({ locale: "en-US" })
+ }))
+ // 2 m/s ≈ 4.5 mph
+ expect(formatSpeed(2)).toBe("4.5 mph")
+ })
+
+ it("formats 0 m/s correctly", () => {
+ // @ts-ignore – mock Intl
+ Intl.NumberFormat = jest.fn(() => ({
+ resolvedOptions: () => ({ locale: "de-DE" })
+ }))
+ expect(formatSpeed(0)).toBe("0.0 km/h")
+ })
+
+ it("falls back to km/h if Intl throws", () => {
+ // @ts-ignore – mock Intl to throw
+ Intl.NumberFormat = jest.fn(() => {
+ throw new Error("unsupported")
+ })
+ expect(formatSpeed(8)).toBe("28.8 km/h")
+ })
+})
diff --git a/apps/mobile/src/utils/geo.ts b/apps/mobile/src/utils/geo.ts
index 461bfe3b..eb913091 100644
--- a/apps/mobile/src/utils/geo.ts
+++ b/apps/mobile/src/utils/geo.ts
@@ -40,6 +40,21 @@ function usesMiles(): boolean {
}
}
+/** Format m/s into a human-readable speed string using the device locale's unit. */
+export function formatSpeed(metersPerSecond: number): string {
+ if (usesMiles()) {
+ const mph = metersPerSecond * 2.23694
+ return `${mph.toFixed(1)} mph`
+ }
+ const kmh = metersPerSecond * 3.6
+ return `${kmh.toFixed(1)} km/h`
+}
+
+/** Return the speed unit info for the current locale (used by map WebView). */
+export function getSpeedUnit(): { factor: number; unit: string } {
+ return usesMiles() ? { factor: 2.23694, unit: "mph" } : { factor: 3.6, unit: "km/h" }
+}
+
/** Format meters into a human-readable string using the device locale's unit. */
export function formatDistance(meters: number): string {
if (usesMiles()) {