I'm working on drawing tools on a map in which I calculate the radius of a circle drawn on a map based on its coordinates. That looks good, but I'm seeing that the circle doesn't perfectly match mouse positioning if it's drawn far from the equator. This is because I use an equation that considers 6,371,000 meters the radius of the Earth. The true radius of the Earth varies based on distance from the equator and I've found that can be calculated with this formula:
latitude B, radius R, radius at equator r1, radius at pole r2
R = √ [ (r1² * cos(B))² (r2² * sin(B))² ] / [ (r1 * cos(B))² (r2 * sin(B))² ]
according to https://rechneronline.de/earth-radius/
How can I write that formula in JavaScript?
CodePudding user response:
Assuming your equation is correct- I'm a programmer, not a geographer; try this:
function square(number) {
return Math.pow(number,2);
}
var lattitude;
const radiusAtEquator = 6371000;
const radiusAtPole = Number.MIN_VALUE;
var radius = Math.sqrt(square(square(radiusAtEquator) * Math.cos(lattitude))) / (square(radiusAtEquator * Math.cos(lattitude)) square(radiusAtPole * Math.sin(lattitude)))
If you meant to take the square root of the whole thing, just remove one ')' from before the '/' and add it on the end. Also, you must give lattitude a numerical value before running the program or it won't work.
CodePudding user response:
I'll write the formula but you can edit it to make it more readable:
function calculateR(B,r1,r2){
const R = Math.sqrt(
((r1*r1 * Math.cos(B))*(r1*r1 * Math.cos(B)) (r2*r2 * Math.sin(B))*(r2*r2 * Math.sin(B)) /
((r1* Math.cos(B))*((r1* Math.cos(B)) (r2*Math.sin(B)*(r2*Math.sin(B)))))))
return R;
}
//call your method here :
console.log(calculateR(1,2,3));
CodePudding user response:
We can always take a peek at how they do it from their source code. Their source is stored here. The relevant calculation is this one:
var z=Math.sqrt((Math.pow(r1*r1*Math.cos(x),2) Math.pow(r2*r2*Math.sin(x),2)) / (Math.pow(r1*Math.cos(x),2) Math.pow(r2*Math.sin(x),2)));
But it has a lot of redundant calculations. We can optimize it like so:
function getSpheroidRadius(B, r1, r2)
{
if (Math.abs(B) > 90)
throw Error('Invalid Latitude value supplied: ' B);
let r1Sq = r1 * r1;
let r2Sq = r2 * r2;
let equatorProjectionSq = r1Sq * Math.cos(B) ** 2;
let poleProjectionSq = r2Sq * Math.sin(B) ** 2;
let r = Math.sqrt(
((equatorProjectionSq * r1Sq) (poleProjectionSq * r2Sq))
/ (equatorProjectionSq poleProjectionSq)
);
return r;
}
console.log(getSpheroidRadius(50, 6378.137, 6356.7523));
