我试图在php中使用Haversine Formula来计算两个邮政编码之间的距离;到目前为止,我已经创建了一个函数来计算距离。我的数据库表名为'postcode',字段'postcode_id','postcode','lat','lng'。
<script>
function getDistance($latitude1, $longitude1, $latitude2, $longitude2) {
$earth_radius = 6371;
$postLat = deg2rad($latitude2 - $latitude1);
$postLon = deg2rad($longitude2 - $longitude1);
$a = sin($postLat/2) * sin($postLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($postLon/2) * sin($postLon/2);
$c = 2 * asin(sqrt($a));
$d = $earth_radius * $c;
return $d;
}
</script>
<?php
$postcode_qry = mysqli_query($connect, "SELECT *,(((acos(sin((".$postLat."*pi()/180)) * sin(('lat'*pi()/180))+cos((".$postLat."*pi()/180)) * cos(('lat'*pi()/180)) * cos(((".$postLon."- 'lng')*pi()/180))))*180/pi())*60*1.1515) as distance
FROM `postcode` WHERE distance = ".$d."");
?>
答案 0 :(得分:1)
您可以使用Google服务申请:
function getLongLat($address) {
$url = 'http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&language=nl&address='+$address;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$obj = simplexml_load_string($response);
if ($obj) {
$obj = $obj->result;
return array( 'latitude' => $obj->geometry->location->lat.'', 'longitude' => $obj->geometry->location->lng.'',);
}else{
return [];
}
}
Google会尝试为您解析地址,猜测postal code, Country
应该对您有用,并且您可以将所需数据传递给MySQL
函数