Page 1 of 1

JScript: calculate distance between 2 points

PostPosted: Thu Nov 05, 2015 8:55 pm
by David de Argentina
Hi all,

If you need calculate the distance between 2 points ( in polar coordinates, like google maps style ) feel free to use this function:

Code: Select all
{NeoBook Function}
Version=5.80
Language=JScript
Param=[%1]|Text|Lat 1
Param=[%2]|Text|Long 1
Param=[%3]|Text|Lat 2
Param=[%4]|Text|Long 2
{End}
function measure(lat1, lon1, lat2, lon2) {
  var R = 6378.137;
  var dLat = (lat2 - lat1) * Math.PI / 180;
  var dLon = (lon2 - lon1) * Math.PI / 180;
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *  Math.sin(dLon/2) * Math.sin(dLon/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  return d * 1000;
}

var lat1 = [%1];
var lon1 = [%2];
var lat2 = [%3];
var lon2 = [%4];

nbSetVar ('result', measure(lat1,lon1,lat2,lon2));


Obviously, distance is the measure of the rect line that join both points.
No turns of streets, or curves of the rute, etc

Greetings from Buenos Aires,
David de Argentina

Re: JScript: calculate distance between 2 points

PostPosted: Fri Nov 06, 2015 9:18 am
by dpayer
Good to know David.

There are also Geometric functions within MS SQL:
https://msdn.microsoft.com/en-us/library/bb933808.aspx

and within MySQL:
https://dev.mysql.com/doc/refman/5.7/en ... tions.html

which can be employed.

David P

Re: JScript: calculate distance between 2 points

PostPosted: Fri Nov 06, 2015 11:22 am
by Tony Kroos
Avoid useless declaring, it's too much

Code: Select all
function measure(lat1, lon1, lat2, lon2)
{
  var dLat = (lat2 - lat1) * Math.PI / 180;
  var dLon = (lon2 - lon1) * Math.PI / 180;
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *  Math.sin(dLon/2) * Math.sin(dLon/2);
  return 12756274 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
}
nbSetVar ('result', measure([%1],[%2],[%3],[%4]));