Maurício Lima
Maurício Lima

Reputation: 534

How to measure distance between two coordinates with less calc possible?

I'm trying to make measures using the less CPU possible, so I'm using a constant multiplicator to get to a value in meters like this:

lat1,long1 = Coordinate 1

lat2,long2 = Coordinate 2

DistV := abs(lat1-lat2);                  // Get a positive vertical value
DistH := abs(lon1-long2);                 // Get a positive horizontal value
DistGPS := sqrt(sqr(DistV) + sqr(DistH)); // Get a diagonal value
DistMeters := DistGPS*(111120*0.946);     // 111120*0.946 = Constant multiplicator to meters

However, the values calculated are going to be added to the previous measures, making it necessary to be accurate. Does anyone know a better way for doing it?

Upvotes: 1

Views: 2445

Answers (1)

MBo
MBo

Reputation: 80187

To measure a distance more accurately, you can use Haversine formula, as written in comments. Here you can see formula and JavaScript implementation:

var R = 6371e3; // metres
var φ1 = lat1.toRadians();
var φ2 = lat2.toRadians();
var Δφ = (lat2-lat1).toRadians();
var Δλ = (lon2-lon1).toRadians();

var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
        Math.cos(φ1) * Math.cos(φ2) *
        Math.sin(Δλ/2) * Math.sin(Δλ/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

var d = R * c;

If you think that rough approximation is quite good for you purposes, you can make it more precise accounting for distance contraction along meridian (instead of common constant for both coordinates):

DistV := abs(lat1-lat2);                  // Get a positive vertical value
DistH := abs(lon1-long2);                 // Get a positive horizontal    value
DistH := DistH * Cos((lat1+lat2) / 2);     // Use average latitude            
DistGPS := sqrt(sqr(DistV) + sqr(DistH)); // Get a diagonal value
DistMeters := DistGPS*111120;  //to meters

Upvotes: 7

Related Questions