Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Increase latitude accuracy level #102

Merged
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions src/api/coords-to-vector-3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,44 @@ import { MathUtils, Vector3Tuple } from 'three';
import { Coords } from './coords';
import { earthRadius } from "../core/earth-radius";


const mercatorScaleLookup: { [key: number]: number } = {};

function getMercatorScale(lat: number): number {
const index = Math.round(lat * 1000);
if (mercatorScaleLookup[index] === undefined) {
mercatorScaleLookup[index] = 1 / Math.cos(lat * MathUtils.DEG2RAD);
}
return mercatorScaleLookup[index];
}

export function averageMercatorScale(originLat: number, pointLat: number, steps = 10): number {
let totalScale = 0;
const latStep = (pointLat - originLat) / steps;
for (let i = 0; i <= steps; i++) {
const lat = originLat + latStep * i;
totalScale += getMercatorScale(lat);
}
return totalScale / (steps + 1);
}

export function coordsToVector3(point: Coords, origin: Coords): Vector3Tuple {
const latitudeDiff = (point.latitude - origin.latitude) * MathUtils.DEG2RAD;
const longitudeDiff = (point.longitude - origin.longitude) * MathUtils.DEG2RAD;
const altitudeDiff = (point.altitude || 0) - (origin.altitude || 0);

const x = longitudeDiff * earthRadius * Math.cos(origin.latitude * MathUtils.DEG2RAD);
const y = altitudeDiff;
const z = -latitudeDiff * earthRadius;
const zOld = -latitudeDiff * earthRadius;

// dynamic step size based on latitude difference. calculate the mercator unit scale at origin
// and the scale average along the line to the point for better accuracy far from origin
const steps = Math.ceil(Math.abs(point.latitude - origin.latitude)) * 100 + 1;
const absOriginLat = Math.abs(origin.latitude); // use abs values for scale calculation (same scale for north and south)
const absPointLat = Math.abs(point.latitude);
const avgScale = averageMercatorScale(absOriginLat, absPointLat, steps);

const z = (zOld / getMercatorScale(absOriginLat)) * avgScale;

return [x, y, z] as Vector3Tuple;
}
}
2 changes: 1 addition & 1 deletion src/core/earth-radius.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const earthRadius = 6378137;
export const earthRadius = 6371008.8;
Loading