This is the function by giving the longitude and latitude of the departure and arrival, calculate the distance in kilometers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var lat1 = //start latitude var lon1 = //start longitude var lat2 = //end latitude var lon2 = //end longitude var R = 6371; // now in km (change for get miles) 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; if (d>1) return Math.round(d);//+"km"; else if (d<=1) return Math.round(d*1000)+"m"; return d; |
Of course, this calculation is indicative, that is in linear form (air).
But its strength is that it is a calculation offline, ie without the use of tools such as GPS or internet
Hey Michal.The result is in kileemtros. If you’re wanting to convert it to miles, you can simply remove the * 1.609344 line. Alternatively, if you’re wanting to convert to metres, you’ll need to add on an additioal * 1000 after the conversion to kileemtros.Hope it helps :)