Php Google GetDistance函数工作不正常
Php Google GetDistance函数工作不正常,php,google-maps,google-maps-api-3,geocoding,latitude-longitude,Php,Google Maps,Google Maps Api 3,Geocoding,Latitude Longitude,我试图通过搜索条件中给定位置的距离过滤搜索结果。每个报价都有自己的位置,包括(德国)邮政编码和所属城市。搜索条件包括相同的原则。因此,最终,搜索者的位置和报价的多个位置。此外,所有报价都有一个半径,可以在该半径内操作。然后我想过滤掉所有报价,这些报价与搜索者位置的距离更大,比它们的操作半径大。我使用了以下PHP代码: $position = $_GET['position']!='' ? $_GET['position'] : ''; 从我的URL中获取搜索者的位置 $Results = $d
我试图通过搜索条件中给定位置的距离过滤搜索结果。每个报价都有自己的位置,包括(德国)邮政编码和所属城市。搜索条件包括相同的原则。
因此,最终,搜索者的位置和报价的多个位置。
此外,所有报价都有一个半径,可以在该半径内操作。
然后我想过滤掉所有报价,这些报价与搜索者位置的距离更大,比它们的操作半径大。
我使用了以下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>";
}
这就是我在这个论坛中发现的获取两个地址之间距离的功能。它在大多数情况下都有效,我得到了正确的距离,例如:77.4640983104公里。
但是每运行两到三次,我就会得到以下错误: 注意:尝试获取非对象的属性 及 注意:未定义的偏移量:0 在“从地理数据获取纬度和经度”部分,输出的距离错误为0公里。
我真的不知道我犯了什么错误,但我希望有人能向我解释,应该更改什么,或者整个过程是否以错误的方式进行。
提前非常感谢您,祝您度过愉快的一天 注意: 如果将Google API键添加到URL,则该函数确实有效。
似乎我发现的功能是从使用地图商业化之前开始的 您需要验证
file\u get\u contents
没有遇到错误。这不会删除错误。
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';
}
}