for a project I needed a quick way to calculate the distance between two gps coordinates. I though this code might be handy for others (e.g. in combination with the Geocoder API Plug-in).
Save this as a UDT with the name "calculate_distance"
Code: Select all
//
// Check for parameters, if not set or empty, set default
//
// This parameter is used to select the scaling of the result returned
if (isset($params['convert']) AND ($params['convert'] != '')) {
$convert = strtolower($params['convert']);
} else {$convert = 'mi';}
// This is the latitude of the first point
if (isset($params['gps_lat_1']) AND ($params['gps_lat_1'] != '')) {
$gps_lat_1 = (float)$params['gps_lat_1'];
} else {$gps_lat_1 = -10;}
// This is the latitude of the first point
if (isset($params['gps_lat_2']) AND ($params['gps_lat_2'] != '')) {
$gps_lat_2 = (float)$params['gps_lat_2'];
} else {$gps_lat_2 = 11;}
// This is the longitude of the second point
if (isset($params['gps_long_1']) AND ($params['gps_long_1'] != '')) {
$gps_long_1 = (float)$params['gps_long_1'];
} else {$gps_long_1 = 10;}
// This is the longitude of the second point
if (isset($params['gps_long_2']) AND ($params['gps_long_2'] != '')) {
$gps_long_2 = (float)$params['gps_long_2'];
} else {$gps_long_2 = 11;}
//
// Do the distance calculation
//
$result = sin(deg2rad($gps_lat_1)) * sin(deg2rad($gps_lat_2)) + cos(deg2rad($gps_lat_1)) * cos(deg2rad($gps_lat_2)) * cos(deg2rad($gps_long_1 - $gps_long_2));
$result = rad2deg(acos($result)) * 69.09;
//
// If a converting is required do this
//
if ($convert== 'km' ) {$result = $result * 1.609344;}
//
// Return integer value for distance in selected scaling
//
return (integer)round($result,0);
{calculate_distance convert="km" gps_lat_1=10 gps_lat_2=11.63 gps_long_1=53.5123 gps_long_2=55.123}
The UDT will echo the pure value as integer (default scaling is US miles, optional: kilometer). For other scalings (e.g. nautic miles... just add your scalings below the KM conversion in the same pattern.
Best
Nils