Colota - Android GPS Location tracker
Add daily distance traveled to Location Inspector map tab
Max Dietrich7468e8f68ef6
diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.mdindex d885131b..7216eb82 100644--- a/apps/docs/docs/introduction.md+++ b/apps/docs/docs/introduction.md@@ -30,7 +30,7 @@ Colota has nine screens, each focused on a specific task:| **API Config** | Endpoint field mapping with templates for Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, or custom backends || **Auth Settings** | Endpoint authentication (None, Basic Auth, Bearer Token) and custom HTTP headers || **Geofences** | Create, edit, and delete pause zones on an interactive map |-| **Location History** | Browse recorded locations on a track map with day picker, or as a paginated list with accuracy indicators |+| **Location History** | Browse recorded locations on a track map with day picker and daily distance traveled, or as a paginated list with accuracy indicators || **Export Data** | Export tracked locations as CSV, GeoJSON, GPX, or KML || **Data Management** | Clear sent history, delete old data, vacuum the database || **About** | App version, device info, links to repository and privacy policy |diff --git a/apps/mobile/src/components/features/inspector/DatePicker.tsx b/apps/mobile/src/components/features/inspector/DatePicker.tsxindex b809dd30..7fc0a796 100644--- a/apps/mobile/src/components/features/inspector/DatePicker.tsx+++ b/apps/mobile/src/components/features/inspector/DatePicker.tsx@@ -13,6 +13,7 @@ interface DatePickerProps {date: DateonDateChange: (date: Date) => voidlocationCount: number+ distance?: stringcolors: ThemeColors}@@ -20,7 +21,7 @@ function isSameDay(a: Date, b: Date): boolean {return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()}-export function DatePicker({ date, onDateChange, locationCount, colors }: DatePickerProps) {+export function DatePicker({ date, onDateChange, locationCount, distance, colors }: DatePickerProps) {const isToday = isSameDay(date, new Date())const goBack = () => {@@ -58,6 +59,7 @@ export function DatePicker({ date, onDateChange, locationCount, colors }: DatePi<Text style={[styles.dateText, { color: colors.text }]}>{formatted}</Text><Text style={[styles.countText, { color: colors.textSecondary }]}>{locationCount} {locationCount === 1 ? "location" : "locations"}+ {distance ? ` · ${distance}` : ""}</Text></TouchableOpacity>diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsxindex c335ccc0..41f5fde2 100644--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx@@ -3,7 +3,7 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useState, useEffect, useRef, useCallback, memo } from "react"+import React, { useState, useEffect, useRef, useCallback, useMemo, memo } from "react"import { View, Text, FlatList, StyleSheet, TouchableOpacity, Switch } from "react-native"import { fonts } from "../styles/typography"import { ChevronLeft, ChevronRight } from "lucide-react-native"@@ -15,6 +15,7 @@ import { STATS_REFRESH_FAST } from "../constants"import { logger } from "../utils/logger"import { DatePicker } from "../components/features/inspector/DatePicker"import { TrackMap } from "../components/features/inspector/TrackMap"+import { computeTotalDistance, formatDistance } from "../utils/geo"// Typesinterface LocationData {@@ -130,6 +131,12 @@ export function LocationHistoryScreen() {const [trackLocations, setTrackLocations] = useState<LocationData[]>([])const [selectedPoint, setSelectedPoint] = useState<{ latitude: number; longitude: number } | null>(null)+ const dailyDistance = useMemo(() => {+ if (trackLocations.length < 2) return undefined+ const meters = computeTotalDistance(trackLocations)+ return formatDistance(meters)+ }, [trackLocations])+/** Fetches data based on current pagination */const fetchData = useCallback(async () => {try {@@ -227,7 +234,13 @@ export function LocationHistoryScreen() {{activeTab === "map" ? (<View style={styles.mapContainer}>- <DatePicker date={mapDate} onDateChange={setMapDate} locationCount={trackLocations.length} colors={colors} />+ <DatePicker+ date={mapDate}+ onDateChange={setMapDate}+ locationCount={trackLocations.length}+ distance={dailyDistance}+ colors={colors}+ /><TrackMap locations={trackLocations} selectedPoint={selectedPoint} colors={colors} isDark={isDark} /></View>) : (diff --git a/apps/mobile/src/utils/__tests__/geo.test.ts b/apps/mobile/src/utils/__tests__/geo.test.tsnew file mode 100644index 00000000..9940805e--- /dev/null+++ b/apps/mobile/src/utils/__tests__/geo.test.ts@@ -0,0 +1,95 @@+import { computeTotalDistance, formatDistance } from "../geo"++describe("computeTotalDistance", () => {+ it("returns 0 for empty array", () => {+ expect(computeTotalDistance([])).toBe(0)+ })++ it("returns 0 for a single point", () => {+ expect(computeTotalDistance([{ latitude: 48.8566, longitude: 2.3522 }])).toBe(0)+ })++ it("calculates distance between two known points", () => {+ // Berlin (52.52, 13.405) → Munich (48.1351, 11.582) ≈ 504 km+ const locations = [+ { latitude: 52.52, longitude: 13.405 },+ { latitude: 48.1351, longitude: 11.582 }+ ]+ const meters = computeTotalDistance(locations)+ expect(meters).toBeGreaterThan(500_000)+ expect(meters).toBeLessThan(510_000)+ })++ it("sums distances across multiple consecutive points", () => {+ const locations = [+ { latitude: 52.52, longitude: 13.405 },+ { latitude: 52.53, longitude: 13.405 },+ { latitude: 52.54, longitude: 13.405 }+ ]+ // Two hops of ~1.11 km each ≈ 2.22 km total+ const meters = computeTotalDistance(locations)+ expect(meters).toBeGreaterThan(2000)+ expect(meters).toBeLessThan(2500)+ })++ it("returns 0 for identical points", () => {+ const locations = [+ { latitude: 48.8566, longitude: 2.3522 },+ { latitude: 48.8566, longitude: 2.3522 }+ ]+ expect(computeTotalDistance(locations)).toBe(0)+ })+})++describe("formatDistance", () => {+ let originalNumberFormat: typeof Intl.NumberFormat++ beforeEach(() => {+ originalNumberFormat = Intl.NumberFormat+ })++ afterEach(() => {+ // @ts-ignore – restore original+ Intl.NumberFormat = originalNumberFormat+ })++ it("formats as km for non-US locales", () => {+ // @ts-ignore – mock Intl+ Intl.NumberFormat = jest.fn(() => ({+ resolvedOptions: () => ({ locale: "de-DE" })+ }))+ expect(formatDistance(12345)).toBe("12.3 km")+ })++ it("formats as miles for en-US locale", () => {+ // @ts-ignore – mock Intl+ Intl.NumberFormat = jest.fn(() => ({+ resolvedOptions: () => ({ locale: "en-US" })+ }))+ expect(formatDistance(1609.344)).toBe("1.0 mi")+ })++ it("formats as miles for en-GB locale", () => {+ // @ts-ignore – mock Intl+ Intl.NumberFormat = jest.fn(() => ({+ resolvedOptions: () => ({ locale: "en-GB" })+ }))+ expect(formatDistance(8046.72)).toBe("5.0 mi")+ })++ it("formats 0 meters correctly", () => {+ // @ts-ignore – mock Intl+ Intl.NumberFormat = jest.fn(() => ({+ resolvedOptions: () => ({ locale: "de-DE" })+ }))+ expect(formatDistance(0)).toBe("0.0 km")+ })++ it("falls back to km if Intl throws", () => {+ // @ts-ignore – mock Intl to throw+ Intl.NumberFormat = jest.fn(() => {+ throw new Error("unsupported")+ })+ expect(formatDistance(5000)).toBe("5.0 km")+ })+})diff --git a/apps/mobile/src/utils/geo.ts b/apps/mobile/src/utils/geo.tsnew file mode 100644index 00000000..461bfe3b--- /dev/null+++ b/apps/mobile/src/utils/geo.ts@@ -0,0 +1,51 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++const EARTH_RADIUS_METERS = 6371000.0++/** Haversine formula — mirrors GeofenceHelper.kt */+function haversine(lat1: number, lon1: number, lat2: number, lon2: number): number {+ const dLat = ((lat2 - lat1) * Math.PI) / 180+ const dLon = ((lon2 - lon1) * Math.PI) / 180+ const a =+ Math.sin(dLat / 2) ** 2 ++ Math.cos((lat1 * Math.PI) / 180) * Math.cos((lat2 * Math.PI) / 180) * Math.sin(dLon / 2) ** 2+ return EARTH_RADIUS_METERS * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))+}++/** Sum of Haversine distances between consecutive points, in meters. */+export function computeTotalDistance(locations: { latitude: number; longitude: number }[]): number {+ let total = 0+ for (let i = 1; i < locations.length; i++) {+ total += haversine(+ locations[i - 1].latitude,+ locations[i - 1].longitude,+ locations[i].latitude,+ locations[i].longitude+ )+ }+ return total+}++const MILE_LOCALES = new Set(["en-US", "en-GB", "en-MM", "en-LR"])++function usesMiles(): boolean {+ try {+ const locale = Intl.NumberFormat().resolvedOptions().locale+ return MILE_LOCALES.has(locale)+ } catch {+ return false+ }+}++/** Format meters into a human-readable string using the device locale's unit. */+export function formatDistance(meters: number): string {+ if (usesMiles()) {+ const miles = meters / 1609.344+ return `${miles.toFixed(1)} mi`+ }+ const km = meters / 1000+ return `${km.toFixed(1)} km`+}