JScript: calculate distance between 2 points

Questions and information about using VBScript and JavaScript in NeoBook functions

Moderator: Neosoft Support

Locked
David de Argentina
Posts: 1596
Joined: Mon Apr 04, 2005 4:13 pm
Location: Buenos Aires, Argentina
Contact:

JScript: calculate distance between 2 points

Post 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
User avatar
dpayer
Posts: 1394
Joined: Mon Apr 11, 2005 5:55 am
Location: Iowa - USA

Re: JScript: calculate distance between 2 points

Post 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
David Payer
Des Moines, Iowa
USA
Tony Kroos
Posts: 419
Joined: Thu Oct 15, 2009 3:43 pm

Re: JScript: calculate distance between 2 points

Post 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]));
Locked