-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.php
140 lines (114 loc) · 2.46 KB
/
index.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
<?php
/**
* Class City
*
* @author Andrew Kus
*/
class City {
/**
* Keep coordinates of the city
*/
private $city = array();
public function __construct($city) {
$cities = $this->getCities();
$this->city = $cities[$city];
}
/**
* Returns cities
*
* @return array
*/
private function getCities() {
return array(
'Birmingham' => array(
52.4666670,
1.8833330
),
'Bradford' => array(
53.8000000,
1.7521000
),
'Bristol' => array(
51.4500000,
2.5833000
),
'Edinburgh' => array(
55.9531000,
3.1889000
),
'Glasgow' => array(
55.8580000,
4.2590000
),
'Leeds' => array(
53.7997000,
1.5492000
),
'Liverpool' => array(
53.4000000,
3.0000000
),
'London' => array(
51.5072000,
0.1275000
),
'Manchester' => array(
53.4667000,
2.3333000
),
'Sheffield' => array(
53.3836000,
1.4669000
)
);
}
/**
* Calculate a distance between two coordinates
* Default in miles
*
* @param float $lat1 lattitute from first location
* @param float $long1 long from first location
* @param float $lat2 lattitute from second location
* @param float $long2 long from second location
* @return float Distance
*/
public function distance($lat1, $lng1, $lat2, $lng2, $miles = true)
{
$pi80 = M_PI / 180;
$lat1 *= $pi80;
$lng1 *= $pi80;
$lat2 *= $pi80;
$lng2 *= $pi80;
$r = 6372.797;
$dlat = $lat2 - $lat1;
$dlng = $lng2 - $lng1;
$a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
$km = $r * $c;
return ($miles ? ($km * 0.621371192) : $km);
}
/**
* Returns list of the nearest cities by distance
*
* @param int $distance distance in miles, default is 100
* @return $result array
*/
public function getCitiesByDistance($distance = 100) {
$result = array();
$currentCity = $this->city;
foreach ($this->getCities() as $city => $coordinates) {
$calculatedDistance = $this->distance($currentCity[0], $currentCity[1], $coordinates[0], $coordinates[1]);
if ($calculatedDistance <= $distance && $calculatedDistance != 0) {
array_push($result, array($calculatedDistance, $city));
}
}
// Sort result by distance
asort($result);
// debug result
echo "<pre>";
print_r($result);
echo "<pre>";
}
}
$liverpool = new City('Liverpool');
$liverpool->getCitiesByDistance(100);