forked from DiliBau/geo-distance
-
Notifications
You must be signed in to change notification settings - Fork 0
/
geo-distance.php
41 lines (41 loc) · 1.45 KB
/
geo-distance.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
define( 'EARTH_RADIUS_MILES', 3959 );
define( 'EARTH_RADIUS_KILOMETERS', 6371 );
/**
* SLC = Spherical Law of Cosines
*/
function distance_slc( $a, $b, $radius = EARTH_RADIUS_MILES ) {
$delta_lat = $b['lat'] - $a['lat'];
$delta_lng = $b['lng'] - $a['lng'];
$distance = sin( deg2rad( $a['lat'] ) ) * sin( deg2rad( $b['lat'] ) ) + cos( deg2rad( $a['lat'] ) ) * cos( deg2rad( $b['lat'] ) ) * cos( deg2rad( $delta_lng ) ) ;
$distance = acos( $distance );
$distance = rad2deg( $distance );
$distance = $distance * 60 * 1.1515;
$distance = round( $distance, 4 );
return $distance;
}
function distance_haversine( $a, $b, $radius = EARTH_RADIUS_MILES ) {
$delta_lat = $b['lat'] - $a['lat'];
$delta_lng = $b['lng'] - $a['lng'];
$alpha = $delta_lat/2;
$beta = $delta_lng/2;
$a1 = sin( deg2rad( $alpha ) ) * sin( deg2rad( $alpha ) ) + cos( deg2rad( $a['lat'] ) ) * cos( deg2rad( $b['lat'] ) ) * sin( deg2rad( $beta ) ) * sin( deg2rad( $beta ) ) ;
$c = asin( min( 1, sqrt( $a1 ) ) );
$distance = 2 * $radius * $c;
$distance = round( $distance, 4 );
return $distance;
}
function distance( $a, $b, $radius = EARTH_RADIUS_MILES, $type = 'haversine' ) {
switch( $type ) {
case 'slc':
return distance_slc( $a, $b, $radius );
break;
case 'haversine':
return distance_haversine( $a, $b, $radius );
break;
default:
# something to be added here
return null;
break;
}
}