根据数据库数据,用lat和long查找最近的位置



我想根据数据库数据中请求的lat和lon找到最近的位置。我混淆了我的代码结果,它的距离是对的还是错的?

$lat= mysql_real_escape_string($_REQUEST['lat']);
$lng= mysql_real_escape_string($_REQUEST['lon']);
$multiplier = 112.12; 
$distance = 20;   
$sql=" SELECT beach.id,county.title,municipality.title,beach.beach_name,beach.description,beach.latitude,beach.longitude,beach.rainfall,beach.temperature,beach.status_id,beach.status_details,beach.notice, (SQRT(POW((beach.latitude - $lat), 2) + POW((beach.longitude - $lng), 2)) * $multiplier) AS distance 
from beach as beach,county as county,municipality as municipality where beach.county_id=county.id and beach.municipality_id=municipality.id  and POW((beach.latitude - $lat), 2) + POW((beach.longitude - $lng), 2) < POW(($distance / $multiplier), 2) ORDER BY distance ASC LIMIT 0 , 3";

两个任意点之间(大圆)距离的正确函数是一个比您使用的复杂得多的公式。

假设"最近的海滩"是指

A) 不靠近北极或南极

B) 不远

C) 如果你有两个非常相似的距离,你不在乎你是否得到了"错误的"一个

然后你可以使用一个与你使用的方程类似的方程,但有几个修正。

具体来说,您的公式需要两个因素。一个因子(您的multiplier从度转换为公里(或英里)。另一个因素解释了这样一个事实,即经度两点之间的距离是纬度的函数。在下面的代码中,我将这两个因子称为$dmult(用于距离)和$lmult(用于纬度校正)。

简单示例:

<?php
$lat = 45;
$lon = 72;
$lat2 = 46;
$lon2 = 73;
$lmult = cos($lat * pi() / 180.0);
$dmult = 40000 / 360; // circumference of earth in km divided by 360 degrees
$dist = $dmult * sqrt(pow($lmult *($lon-$lon2),2) + pow($lat-$lat2,2));
echo "The distance between these points is approximately".$dist."n";
?>

请参阅上的示例http://phpfiddle.org/lite/code/9j6-iet。它给出了大约136公里的距离。如果你想要以英里为单位的距离,你可以定义

$dmult = 24900 / 360;  // circumference in miles divided by 360 degrees

将结果(136公里)与"准确"的在线计算器进行比较:http://boulter.com/gps/distance/?from=N+45+0.0+W+72+0.0&to=N+46+0.0++W+73+0.0&单位=k这给出了135.9km的值-足够靠近海滩工作…

请注意,随着距离的增大,上述计算的结果将变得更加不准确,因为它没有完全考虑到地球的曲率。

如果您需要帮助将其放入查询中,请告诉我——它应该非常简单。

EDIT看起来您并没有将变量的值连接到查询字符串中——换句话说,您看起来像是有了"$multiplier"之类的东西,而应该有"112.12"。在执行查询字符串之前,您需要检查它的外观。将它分配给一个变量(就像您所做的那样),然后打印出来。

最新更新