<?php function distance($lat1, $lon1, $lat2, $lon2) {
$pi80 = M_PI / 180;
$lat1 *= $pi80;
$lon1 *= $pi80;
$lat2 *= $pi80;
$lon2 *= $pi80;
$r = 6372.797; // mean radius of Earth in km
$dlat = $lat2 - $lat1;
$dlon = $lon2 - $lon1;
$a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
$km = $r * $c;
//echo '<br/>'.$km;
$km = $km * 0.621371;
return $km;
}
include_once("dbconnect.php");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$grabCities = "SELECT * FROM cities";
$result = $mysqli->query($grabCities);
while($row = mysqli_fetch_array($result)){
$distance = distance(41.08866717,-81.4780426,$row['lat'],$row['longitude']);
if ($distance < 30){
echo $myCity = $row['City'] . "<BR>";
}
}
$mysqli->close();
?>
答案 0 :(得分:2)
您可以使用MYSQL执行此操作,返回1个结果,这是您想要的结果。
sprintf('
SELECT
*,
(((acos(sin((%1$d*pi()/180)) *
sin((`lat`*pi()/180))+cos((%1$d*pi()/180)) *
cos((`lat`*pi()/180))*cos(((%2$d-`longitude`) *
pi()/180))))*180/pi())
) as distance
FROM `cities`
ORDER BY
distance ASC
LIMIT 1
',
$latitude,
$longitude
);
答案 1 :(得分:0)
这样的东西?未经测试。
$smallestDistance = null;
while($row = mysqli_fetch_array($result)){
$distance = distance(41.08866717,-81.4780426,$row['lat'],$row['longitude']);
if ($distance < $smallestDistance){
$myCity = $row['City'];
}
$smallestDistance = $distance;
}
echo $myCity;