How to calculate the distance between two longitudes at different latitudes?

182 Views Asked by At

I'm creating a program and I need to know if an object on the globe moves more on the Y axis or on the X axis. To do it, I need to get the distance in meters between two latitudes and two longitudes.

// Calculates the distance between two latitudes.
angle = latitude2 - latitude1;
radius = 6378.137 * 1000;
metersPerDegree = (radius * Math.PI * 2 / 360);
print("The distance traveled on the Y axis (latitude) is: " + (angle * metersPerDegree));

The problem is that for the longitude, I can't use the code above. This is because the circumference of the sphere (in this case, of the Earth) varies as latitude increases or decreases.

angle = 89; // Latitude = 89°
print(metersPerDegree * Math.cos(angle * Math.PI/180)); // 1942.79 meters for each degree of longitude
angle = 57; // Latitude = 57°
print(metersPerDegree * Math.cos(angle * Math.PI/180)); // 60628.94 meters for each degree of longitude

My question is: how do I calculate the longitudinal distance between two coordinates?