【发布时间】:2017-02-07 20:57:47
【问题描述】:
我正在尝试通过搜索结果到搜索条件中给定位置的距离来过滤搜索结果。每个报价都有自己的位置,包括(德国)邮政编码和属于它的城市。搜索条件包含同样的原则。
所以在End里面,有搜索者的位置,还有多个offer的位置。
另外,所有offer都有一个半径,在他们可以操作。
然后我想过滤掉所有与搜索者位置的距离大于操作半径的报价。
我使用了这个 PHP 代码:
$position = $_GET['position']!='' ? $_GET['position'] : '';
从我的 URL 中获取搜索者的位置。
$Results = $database->SearchResults('Conditions of the database Query');
根据 URL 中的信息构建查询并搜索我的数据库。
while ($row = mysqli_fetch_array($Results)) {
echo $functions->GetDistance($position, $row[1], "K")."<br>";
}
这个while循环应该告诉我每个offer到搜索者位置的距离
function getDistance($addressFrom, $addressTo, $unit){
//Change address format
$formattedAddrFrom = str_replace(' ','+',$addressFrom);
$formattedAddrTo = str_replace(' ','+',$addressTo);
//Send request and receive json data
$geocodeFrom = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedAddrFrom.'&sensor=false');
$outputFrom = json_decode($geocodeFrom);
$geocodeTo = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedAddrTo.'&sensor=false');
$outputTo = json_decode($geocodeTo);
//Get latitude and longitude from geo data
$latitudeFrom = $outputFrom->results[0]->geometry->location->lat;
$longitudeFrom = $outputFrom->results[0]->geometry->location->lng;
$latitudeTo = $outputTo->results[0]->geometry->location->lat;
$longitudeTo = $outputTo->results[0]->geometry->location->lng;
//Calculate distance from latitude and longitude
$theta = $longitudeFrom - $longitudeTo;
$dist = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) + cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344).' km';
}
else if ($unit == "N") {
return ($miles * 0.8684).' nm';
}
else {
return $miles.' mi';
}
}
这就是我在这个论坛中找到的功能,用于获取两个地址之间的距离。
它在大多数情况下都有效,并且我得到了正确的距离,例如:77.4640983104 公里。
但是每运行两三次,我就会收到此错误:
注意:试图获取非对象的属性
和
注意:未定义的偏移量:0
在“从地理数据中获取纬度和经度”部分,输出错误的距离为 0 公里。
我真的不知道我在做什么,但我希望有人能解释一下对我来说,应该改变什么,或者整个事情是否以错误的方式处理。
非常感谢您,祝您有美好的一天!
【问题讨论】:
-
您需要验证
file_get_contents没有遇到错误。 -
这不会删除错误。
标签: php google-maps google-maps-api-3 geocoding latitude-longitude