Skip to content

Commit

Permalink
fix: only calculate device heading offset is user is in a straight + …
Browse files Browse the repository at this point in the history
…some small errors fixed
  • Loading branch information
afonsosousah committed Jun 7, 2024
1 parent 43ed79d commit 8597ee6
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 26 deletions.
2 changes: 2 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,12 @@

<!-- Dev info -->
<div id="devInfo">
<div id="posAngles"></div>
<div id="headingSource"></div>
<div id="heading"></div>
<div id="headingOffset"></div>
<div id="distanceBetweenUpdates"></div>
<div id="speedMS"></div>
</div>

<!-- Scripts -->
Expand Down
20 changes: 13 additions & 7 deletions scripts/extras.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,6 @@ function toPascalCase(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}

function convertBbox(bbox) {
const minCoords = ol.proj.fromLonLat([bbox[0], bbox[1]]);
const maxCoords = ol.proj.fromLonLat([bbox[2], bbox[3]]);

return [...minCoords, ...maxCoords];
}

function htmlEncode(str) {
return str
.replaceAll("&", "&amp;")
Expand Down Expand Up @@ -215,6 +208,19 @@ function formatDistance(meters) {
return meters.toFixed(0) + "m";
}

const arrayStandardDeviation = (arr, usePopulation = false) => {
// Calculate the mean of the array
const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length;

// Calculate the sum of squared differences from the mean
const sumOfSquaredDifferences = arr
.reduce((acc, val) => acc.concat((val - mean) ** 2), [])
.reduce((acc, val) => acc + val, 0);

// Calculate the standard deviation
return Math.sqrt(sumOfSquaredDifferences / (arr.length - (usePopulation ? 0 : 1)));
};

// Testing functions
let onFakeTrip = false;

Expand Down
45 changes: 37 additions & 8 deletions scripts/map.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ let gpsHeading = null;
let followLocation = false;
let deviceHeadingOffset = 0; // offset between the gps heading when above 5kph and the device compass (to make the device compass reading more accurate)
let watchPositionIDs = [];
let last5PositionsAngles = [];
let inStraightLine = false;

async function initMap() {
// Set cycleways style
Expand Down Expand Up @@ -337,16 +339,43 @@ function getLocation(zoom = true) {
// Location update handler
const locationUpdateHandler = async position => {
// Convert to the OpenLayers format
pos = [position.coords.longitude, position.coords.latitude];
new_pos = [position.coords.longitude, position.coords.latitude];

// Get the differences between new and old positions
if (pos) {
const diffLat = new_pos[1] - pos[1];
const diffLon = new_pos[0] - pos[0];

// Get the angle between new and old positions (corrected from clockwise east to clockwise north)
last5PositionsAngles.push(-90 * (Math.PI / 180) + Math.atan2(diffLat, diffLon));
if (last5PositionsAngles.length > 5) last5PositionsAngles.shift();
}
arrayStandardDeviation(last5PositionsAngles) < 0.15 ? (inStraightLine = true) : (inStraightLine = false);
document.querySelectorAll("#posAngles").forEach(elem => {
if (inStraightLine) {
elem.innerHTML = "in straight";
elem.style.backgroundColor = "green";
} else {
elem.innerHTML = "not straight";
elem.style.backgroundColor = "red";
}
});

// Now update to current pos to new pos, since we don't need the old value
pos = new_pos;

// Get speed
speed = position.coords.speed ?? 0;
if (document.getElementById("speedMS")) document.getElementById("speedMS").innerHTML = speed.toFixed(0) + "m/s";

// Update gps heading
gpsHeading = (Math.PI / 180) * position.coords.heading; // adjusted to radians

// Update speed on landscape
const speedKMH = (speed * 60 * 60) / 1000;
const speedElem = document.getElementById("speed");
if (speedElem) speedElem.innerHTML = speedKMH.toFixed(0); // convert m/s to km/h
for (const speedElem of document.querySelectorAll("#speed")) {
speedElem.innerHTML = speedKMH.toFixed(0); // convert m/s to km/h
}

// Update distance to open station
if (lastStationObj) {
Expand Down Expand Up @@ -390,8 +419,8 @@ function getLocation(zoom = true) {
//map.getView().setCenter(ol.proj.fromLonLat(pos));
}

// Use GPS heading above certain speed (12kph) (testing for more accurate heading)
if (gpsHeading && speed >= (12 * 1000) / (60 * 60)) {
// Use GPS heading if user is ruffly in a straight line for the last 5 seconds
if (gpsHeading && inStraightLine) {
// Calculate offset between gps heading and compass heading
deviceHeadingOffset = Math.PI - Math.abs(Math.abs(gpsHeading - compassHeading) - Math.PI);

Expand Down Expand Up @@ -474,15 +503,15 @@ function startLocationDotRotation() {

if (!pos) return;

// Reset offset if there is no gps heading
if (!gpsHeading) {
// Reset offset if there is not using gps heading
/*if (!(gpsHeading && inStraightLine)) {
// Reset offset
deviceHeadingOffset = 0;
// Dev info
document.getElementById("headingSource").innerHTML = "Compass";
document.getElementById("headingSource").style.backgroundColor = "lightblue";
}
}*/

// Calculate final heading
heading = compassHeading + deviceHeadingOffset;
Expand Down
8 changes: 4 additions & 4 deletions scripts/navigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ async function startNavigation(walkingOnly = false) {
}

// Navigation on-foot from user location to nearest station
navigationMode === "foot";
navigationMode = "foot";

// Set rotation mode
rotationMode = "route";
Expand Down Expand Up @@ -123,7 +123,7 @@ async function finalOnFootNavigation() {
const navigationElements = Array.from(document.querySelectorAll("*")).filter(
e => getComputedStyle(e).zIndex === "16"
);
for (element of navigationElements) {
for (const element of navigationElements) {
element.remove();
}

Expand Down Expand Up @@ -166,7 +166,7 @@ async function stopNavigation() {
e =>
getComputedStyle(e).zIndex === "11" || getComputedStyle(e).zIndex === "16" || getComputedStyle(e).zIndex === "20"
);
for (element of navigationElements) {
for (const element of navigationElements) {
element.remove();
}

Expand Down Expand Up @@ -486,7 +486,7 @@ function exitLandscapeNavigationUI() {
const navigationElements = Array.from(document.querySelectorAll("*")).filter(
e => getComputedStyle(e).zIndex === "16" || getComputedStyle(e).zIndex === "20"
);
for (element of navigationElements) {
for (const element of navigationElements) {
element.remove();
}

Expand Down
12 changes: 5 additions & 7 deletions scripts/routing.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ async function calculateFullRoute(fromCoordinates, toCoordinates) {
let grabStation;
let dropoffStationInternal;

for (stationStart of nearestStationsStart) {
for (stationEnd of nearestStationsEnd) {
for (const stationStart of nearestStationsStart) {
for (const stationEnd of nearestStationsEnd) {
const walkingDistanceToStartStation = distance(fromCoordinates, [stationStart.longitude, stationStart.latitude]);
const cyclingDistanceFromStartToEnd = distance(
[stationStart.longitude, stationStart.latitude],
Expand Down Expand Up @@ -227,8 +227,8 @@ async function recalculateFullRoute(fromCoordinates, toCoordinates) {
let grabStation;
let dropoffStationInternal;

for (stationStart of nearestStationsStart) {
for (stationEnd of nearestStationsEnd) {
for (const stationStart of nearestStationsStart) {
for (const stationEnd of nearestStationsEnd) {
const walkingDistanceToStartStation = distance(fromCoordinates, [stationStart.longitude, stationStart.latitude]);
const cyclingDistanceFromStartToEnd = distance(
[stationStart.longitude, stationStart.latitude],
Expand Down Expand Up @@ -347,15 +347,13 @@ async function calculateRoute(fromCoordinates, toCoordinates, cycling = true) {
cycling: new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#79C000",
width: 8,
width: 4,
}),
zIndex: 0,
}),
walking: new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#231F20",
width: 8,
lineDash: [3, 9],
width: 4,
}),
Expand Down Expand Up @@ -755,7 +753,7 @@ function viewRoute(toCoordinates) {
getLocation(false);

checkPos = function (toCoordinates) {
if (typeof pos === "undefined" || typeof pos === "null") setTimeout(() => checkPos(toCoordinates), 0);
if (typeof pos === "undefined") setTimeout(() => checkPos(toCoordinates), 0);
else {
// Calculate and display the route on the map when we have the user position
calculateFullRoute(pos, toCoordinates);
Expand Down

0 comments on commit 8597ee6

Please sign in to comment.