ProximityTrait.php in Geolocation Field 8.3
File
src/ProximityTrait.php
View source
<?php
namespace Drupal\geolocation;
trait ProximityTrait {
public static function getDistanceConversions($unit = NULL) {
$conversions = [
'km' => 1,
'mi' => 1.609344,
'nm' => 1.852,
'm' => 0.001,
'ly' => 9460753090819,
];
if (!empty($conversions[$unit])) {
return $conversions[$unit];
}
return $conversions;
}
public static function convertDistance($value, $factor = NULL, $invert = FALSE) {
$value = (double) $value;
if (empty($factor)) {
$factor = self::getDistanceConversions('mi');
}
if (is_string($factor) && !empty(self::getDistanceConversions($factor))) {
$factor = self::getDistanceConversions($factor);
}
if (is_numeric($factor)) {
if ($invert) {
return (double) $value / $factor;
}
return (double) $value * $factor;
}
return FALSE;
}
public static function getProximityQueryFragment($table_name, $field_id, $filter_lat, $filter_lng) {
$field_latsin = "{$table_name}.{$field_id}_lat_sin";
$field_latcos = "{$table_name}.{$field_id}_lat_cos";
$field_lng = "{$table_name}.{$field_id}_lng_rad";
$filter_lat = empty($filter_lat) ? 0 : $filter_lat;
$filter_lng = empty($filter_lng) ? 0 : $filter_lng;
$filter_latcos = cos(deg2rad($filter_lat));
$filter_latsin = sin(deg2rad($filter_lat));
$filter_lng = deg2rad($filter_lng);
return "(\n ACOS(LEAST(1,\n {$filter_latcos}\n * {$field_latcos}\n * COS( {$filter_lng} - {$field_lng} )\n +\n {$filter_latsin}\n * {$field_latsin}\n )) * 6371\n )";
}
}