Calculate Distance Between Two Points

My Smartapp, under development atm, can determine at any given moment the current Lat/Lon position of my mobile. It also has the Lat/Lon coordinates of my home. My question is, is it possible within groovy , to calculate the distance between the current mobile position and my home? I already have this ability within JS but not sure how I could use (or call) such script within my smartapp.

In case you are wondering. Here is the JS function used to calc the distance

var R2D = 180 / Math.PI;
var D2R = Math.PI / 180;

/**************************************************************************************************/
function groundDistance(toLat,toLon,fromLat,fromLon) {
toLatRad = toLat * D2R
toLonRad = toLon * D2R
fromLatRad = fromLat * D2R
fromLonRad = fromLon * D2R
x = (Math.sin(fromLatRad) * Math.sin(toLatRad)) + (Math.cos(fromLatRad) * Math.cos(toLatRad) * Math.cos(fromLonRad - toLonRad))
if(x >= 1)
return 0
else
return 60 * ((Math.atan(-x / Math.sqrt(-x * x + 1)) + 2 * Math.atan(1)) * R2D)
}

Have you tried Google Translate to convert JS to Groovy? (Sorry, could not resist) :slight_smile:

3 Likes

Groovy is based off Java. Here are some docs that may help you with the math differences.
http://www.groovy-lang.org/differences.html
http://www.groovy-lang.org/structure.html

Chances are everything youā€™re trying to do has already been done, or someone has something close that can be easily adapted.

You can probably reuse most of this code:

Thanks everyone. Decided that since I had an Apache web server with php running I would go that route. Simply:

<?php

$toLat= $_GET[ā€˜toLatā€™] ;
$toLon= $_GET[ā€˜toLonā€™] ;
$fromLat= $_GET[ā€˜fromLatā€™] ;
$fromLon= $_GET[ā€˜fromLonā€™] ;
$unit= $_GET[ā€˜unitā€™] ;

function getDist($lat1, $lon1, $lat2, $lon2, $unit) {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == ā€œKā€) { // Return Kilometers
return ($miles * 1.609344);
}
else if ($unit == ā€œMā€) { // Return Meters
return ($miles * 1609.344);
}
else if ($unit == ā€œFā€) { // Return Feet
return ($miles * 5280);
}
else { // Return Miles
return $miles;

  		}

}

header(ā€˜Content=Type: application/jsonā€™); // only way I could get the output trimmed of spaces
echo getDist($toLat, $toLon, $fromLat, $fromLon, $unit);

Then my Smartapp contains:

  httpGet("http://www.something.com:portid/getDistance.php?toLat=44&toLon=-77&fromLat=45&fromLon=-78&unit=m") {response ->
        def dist = response.data
        log.debug "Distance between in Meters: $dist"
     }

Haversine function in Groovy:

2 Likes

Very niceā€¦ Thank you :+1: