我有一个表格,我在其中存储服务,服务表的列是固定,经度,即服务的位置。
现在我想获取用户的当前位置,并搜索距离用户大约10公里的可用服务。
为此我搜索了如何计算两个位置之间的距离并尝试了其中一个代码,但它在JSON中给了我一些语法错误。
错误是语法错误,(意外' S'),我也不会通过此公式得到公里数。
public function searchVendors($lattitudeFrom,$longitudeFrom)
{
$lattitudeTo = -10.4212157;
$longitudeTo = 28.6031842;
$dist = $this -> haversineGreatCircleDistance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000);
return $dist;
}
public function haversineGreatCircleDistance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)
{
// convert from degrees to radians
$latFrom = deg2rad($latitudeFrom);
$lonFrom = deg2rad($longitudeFrom);
$latTo = deg2rad($latitudeTo);
$lonTo = deg2rad($longitudeTo);
$latDelta = $latTo - $latFrom;
$lonDelta = $lonTo - $lonFrom;
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
return $angle * $earthRadius;
}
getVendors.php
<?php
header("Content-type: application/json");
// if ( $_SERVER['REQUEST_METHOD']=='POST') {
include_once ("../include/Vendor.php");
try {
$con = DB::getConnection();
$raw = file_get_contents("php://input");
$data = json_decode($raw, true);
$longitude = $data->longitude;
$lattitude = $data->lattitude;
$v = new Vendor();
$response = $v -> searchVendors($lattitude,$longitude);
json_encode($response);
echo $response;
if ( $response == null ) {
$response = json_encode(array("result" => -2, "message" => "Empty result"));
echo $response;
} else {
echo $response;
}
} catch(Exception $e) {
$result = array("result" => -1, "message" => $e -> getMessage());
echo json_encode($result);
}
//}
?>
我怎样才能做到这一点?任何人都可以帮忙...在PHP中非常新。
答案 0 :(得分:0)
php cal_dist(a,b,key = none,spec = km)
答案 1 :(得分:0)
尝试使用此代码查找KM或MILES中的距离
function distance($lat1, $lon1, $lat2, $lon2, $unit) {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}