-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspeedometer.js
56 lines (50 loc) · 1.38 KB
/
speedometer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
let watchId;
const speedLimit = 60; // in km/h
function startSpeedometer()
{
if (navigator.geolocation)
{
watchId = navigator.geolocation.watchPosition(displaySpeed, handleError, {
enableHighAccuracy: true
});
}
else
{
alert("Geolocation is not supported by this browser.");
}
}
function stopSpeedometer()
{
if (watchId)
{
navigator.geolocation.clearWatch(watchId);
document.getElementById("current-speed").textContent = "0 km/h";
document.getElementById("speed-warning").textContent = "";
}
}
function displaySpeed(position)
{
const speedElement = document.getElementById("current-speed");
const speed = position.coords.speed; // Speed in m/s
if (speed !== null)
{
const speedKmH = speed * 3.6; // Convert speed to km/h
speedElement.textContent = speedKmH.toFixed(2) + " km/h";
if (speedKmH > speedLimit)
{
document.getElementById("speed-warning").textContent = "Warning: You are exceeding the speed limit!";
}
else
{
document.getElementById("speed-warning").textContent = "";
}
}
else
{
speedElement.textContent = "N/A";
}
}
function handleError(error)
{
console.error("Error getting current position:", error);
}