我有一个表(用户邮政编码),其中包含用户的邮政编码、纬度和经度。我在 stackoverflow 上找到了一个函数,可以查找特定半径内的邮政编码:
function zipcodeRadius($lat, $lon, $radius) {
global $mysqli;
$zipcodeList = array();
$radius = ($radius ? $radius : 20);
$sql = "SELECT userID,city,zip_code,country FROM user_zip_codes WHERE (3958*3.1415926*sqrt((lat-$lat)*(lat-$lat) + cos(lat/57.29578)*cos($lat/57.29578)*(lon-$lon)*(lon-$lon))/180) <= $radius GROUP BY zip_code";
if($stmt = $mysqli->prepare($sql)) {
$stmt->execute();
$stmt->bind_result($userID,$city,$zip_code,$country);
while($stmt->fetch()) {
$zipcodeList[] = array('userID'=>$userID,'city'=>$city,'zip_code'=>$zip_code,'country'=>$country);
}
}
return $zipcodeList;
}
它工作完美。但是,我希望该函数可以按距离对数组进行排序(按 ASC 或 DESC)。我应该如何调整我的查询才能发生这种情况?
提前致谢。
UPDATE:“距离”这个词可能显得模棱两可(感谢豪尔赫)。我只是希望按距离(即两点之间的距离)对邮政编码进行排序。
你可以使用类似的东西
$iDistance = 20;
$iRadius = 6371; // earth radius in km
$iRadius = 3958; // earth radius in miles
$fLat = x.y; // Your position latitude
$fLon = x.y; // Your position longitude
$strQuery = "
SELECT
*,
$iRadius * 2 * ASIN(SQRT(POWER(SIN(( $fLat - abs(pos.lat)) * pi() / 180 / 2),2) +
COS( $fLat * pi()/180) * COS(abs(pos.lat) * pi() / 180) * POWER(SIN(( $fLon - pos.lon) *
pi() / 180 / 2), 2) )) AS distance
FROM user_zip_codes pos
HAVING distance < $iDistance
ORDER BY distance";
在使用 SQL 之前,您必须获取纬度/经度值。这对我有用
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)