Created
February 2, 2021 00:25
-
-
Save Zerquix18/e3164483b7e2ecd3de39282e8a909826 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useCallback, useEffect, useState } from 'react'; | |
import { Button } from 'semantic-ui-react'; | |
import { MapLatLng } from '../../../../../../../../../models'; | |
import { computeDistanceBetween } from '../../../../../../../../../utils'; | |
type Position = { date: Date; position: MapLatLng }; | |
const MAX_POSITIONS = 3; | |
const Speedometer: React.FC = () => { | |
const [positions, setPositions] = useState<Position[]>([]); | |
const storePosition = useCallback(async (position: MapLatLng) => { | |
const date = new Date(); | |
setPositions((positions) => { | |
if (positions.length >= MAX_POSITIONS) { | |
positions.shift(); | |
} | |
positions.push({ position, date }); | |
return positions; | |
}); | |
}, []); | |
useEffect(() => { | |
const watchId = navigator.geolocation.watchPosition(position => { | |
const { coords: { latitude: lat, longitude: lng } } = position; | |
storePosition({ lat, lng }); | |
}, () => {}, { enableHighAccuracy: true, maximumAge: 1000, timeout: 5000 }); | |
return () => { | |
navigator.geolocation.clearWatch(watchId); | |
}; | |
}, [storePosition]); | |
const speeds = positions.map((position, index, array) => { | |
const previous = array[index - 1]; | |
if (! previous) { | |
return 0; | |
} | |
const time = (position.date.valueOf() / 1000) - (previous.date.valueOf() / 1000); | |
const distance = computeDistanceBetween(previous.position, position.position); | |
return distance / time; | |
}); | |
const speed = speeds.length > 0 ? speeds.reduce((total, current) => total + current, 0) / speeds.length : 0; | |
return ( | |
<Button circular> | |
{ (speed * 3.6).toFixed(2) } km/h | |
</Button> | |
); | |
}; | |
export default Speedometer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
JS/class components: