I'm trying to do trigonometry in JavaScript. When I try run this code in the terminal:
function angle(deg, min, sec) { return (deg) (min / 60) (sec / 3600); }
let deg2 = 89, min2 = 45, sec2 = 0, dist2 = 11.27;
let lat2 = (Math.sin(angle(deg2, min2, sec2))) * dist2;
let long2 = (Math.cos(angle(deg2, min2, sec2))) * dist2;
console.log("lat2 , long2 : " lat2 " , " long2);
I get this:
lat2 , long2 : 11.011462356910855 , -2.400124322266507
instead of this:
lat2 , long2 : 11.269892717722677 , 0.049174495639093
I tried swapping the cos
and sin
with each other but no luck. Also tried to replace cos
with tan
and still different result. Also replaced sin
with tan
and still not correct.
CodePudding user response:
You should break your problem into smaller chunks.
Create functions for converting:
- Sexagesimal degrees (DMS) to decimal degrees
- Decimal degrees to radians
- Radians and distance to coordinates (latitude and longitude)
Note: Functions that end with a "2" are "overloaded methods" that take an object instead of a list of parameters. This is for purely for convenience.
const
toDecimalDegrees = (degrees, minutes, seconds) =>
degrees (minutes / 60) (seconds / 3600),
toDecimalDegrees2 = ({ degrees, minutes, seconds }) =>
toDecimalDegrees(degrees, minutes, seconds),
toRadians = (degrees) =>
degrees * (Math.PI / 180),
toCoordinates = (degrees, minutes, seconds, distance = 0) =>
(angle => ({
latitude: Math.sin(angle) * distance,
longitude: Math.cos(angle) * distance
}))
(toRadians(toDecimalDegrees(degrees, minutes, seconds))),
toCoordinates2 = ({ degrees, minutes, seconds }, distance) =>
toCoordinates(degrees, minutes, seconds, distance);
const
angle = { degrees: 89, minutes: 45, seconds: 0 },
distance = 11.27,
coordinates = toCoordinates2(angle, distance);
console.log(coordinates);
CodePudding user response:
Trigonometry functions expects the angle in radians not degrees. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sin https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cos
function angle(deg, min, sec) {
return (deg) (min / 60) (sec / 3600);
}
let deg2 = 89,
min2 = 45,
sec2 = 0,
dist2 = 11.27;
let lat2 = Math.sin(Math.PI * angle(deg2, min2, sec2) / 180) * dist2;
let long2 = Math.cos(Math.PI * angle(deg2, min2, sec2) / 180) * dist2;
console.log("lat2 , long2 : " lat2 " , " long2);