根据php中的一个邮政编码查找最近的邮政编码
我有一个包含所有州邮政编码的数据库。我在数据库中配置了它,字段是postcode、lat、log。 如果我在表格中给出一个邮政编码并提交,那么我必须通过指定有限的公里数来获得最近的邮政编码。 有没有php代码可以做到这一点? 请帮我做这个 我找到了一些代码来计算距离根据php中的一个邮政编码查找最近的邮政编码,php,Php,我有一个包含所有州邮政编码的数据库。我在数据库中配置了它,字段是postcode、lat、log。 如果我在表格中给出一个邮政编码并提交,那么我必须通过指定有限的公里数来获得最近的邮政编码。 有没有php代码可以做到这一点? 请帮我做这个 我找到了一些代码来计算距离 <?php function getDistance($latitude1, $longitude1, $latitude2, $longitude2) { $earth_radius = 6371;
<?php
function getDistance($latitude1, $longitude1, $latitude2, $longitude2) {
$earth_radius = 6371;
$dLat = deg2rad($latitude2 - $latitude1);
$dLon = deg2rad($longitude2 - $longitude1);
$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2);
$c = 2 * asin(sqrt($a));
$d = $earth_radius * $c;
return $d;
}
?>
例如,如何根据一个邮政编码查找最近的邮政编码。您可以使用sql查询选择距离内的所有邮政编码
在php中,查找最近的邮政编码不是我要做的事情,而是在数据库本身。例如,请参阅关于使用mysql进行地理/空间搜索的演示:如果必须使用php进行搜索,那么您已经完成了一半。您有一个方法,它获取2对与每个邮政编码关联的lat和lon,并返回它们之间的距离。因此,您可以轻松地将您的邮政编码与所有其他邮政编码进行比较,然后找到距离最小的邮政编码。如果您遇到任何问题,请随意展开您的问题。完全同意dbrumann,在MySQL中进行计算,只返回相关结果。否则,您将需要首先从数据库中获取所有邮政编码,这会造成很大的开销。您也可以将PHP计算应用到MySQL,它提供了类似的功能。sql注入万岁!
$distance=$_POST['specified_distance'];
$search_postcode=$_POST['specified_postcode'];
//use search postcode to get the row form database assume it to be searchrow
$latitude=$searchrow['lat'];
$longitude=$searchrow['long'];
$sql = "SELECT *,(((acos(sin((".$latitude."*pi()/180)) * sin((`lat`*pi()/180))+cos((".$latitude."*pi()/180))
* cos((`lat`*pi()/180)) * cos(((".$longitude."- `long`)*pi()/180))))*180/pi())*60*1.1515*1.609344)
as distance
FROM `MyTable`
WHERE distance <= ".$distance;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$postcode_rows=array();
while($row = $result->fetch_assoc()) {
$postcode_rows[$row['distance']]=$row; //get each row to associative //array with distance as key
}
//do array krsort to get the least distance row;
$sorted_postcodes_rows=krsort($postcodes);
$selected_postcode_row=array_shift($sorted_postcodes); //get the nearest post //code
echo =$nearest_postcode=$selected_postcode_row['postcode'];
} else {
echo "No nearest postalcode";
}