绑定距离参数来自hasrsine公式与mysqli

时间:2014-01-02 20:03:14

标签: php mysql mysqli haversine

我正在开设一个网站,该网站会显示最近的商店位置到特定位置。我使用hasrsine公式来确定距离,一切正常,但XML无法看到我创建的距离字段。

switch($unit) {
  case "km":
    $distance = 6371; // KM
    break;
  case "mi":
    $distance = 3959; // KM
    break;
}

$query = "SELECT store_id, name, address, description, longitude, latitude, 
    (? * acos(cos(radians(?)) * cos( radians(latitude)) * cos(radians(longitude)
     - radians(?)) + sin(radians(?)) * sin(radians(latitude)))) 
    AS distanceFromLocation FROM stores";



$stmt = $mysqli->prepare($query);
$stmt->bind_param('iddd', $distance, $user_latitude, $user_longitude, $user_latitude);

$valid_statement = true;
try {
  $stmt->execute();
  $stmt->store_result();
} catch(Exception $e) {
  $valid_statement = false;
  error_log($e->getMessage());
}

if($valid_statement) {

  $stmt->bind_result($store_id, $name, $address, $description, $longitude, $latitude, $distanceFromLocation);

  while($stmt->fetch()) {
    echo $distanceFromLocation;
    $node = $dom->createElement("marker");
    $newnode = $parnode->appendChild($node);
    $newnode->setAttribute("storeid", $store_id);
    $newnode->setAttribute("name", $name);
    $newnode->setAttribute("address", $address);
    $newnode->setAttribute("lat", $latitude);
    $newnode->setAttribute("lng", $longitude);
    $newnode->setAttribute("distance", $distanceFromLocation);
  }
}

distanceFromLocation变量在进入while循环时始终为空。我测试了SQL,它将返回正确的距离值。任何想法为什么我无法访问距离场?是因为它是一个计算字段吗?

2 个答案:

答案 0 :(得分:1)

您需要将switch的结果作为第一个参数合并。为清晰起见,我还将$ distance改为$ constant。

switch($unit) {//From User
  case "km":
    $constant = 6371; // KM
    break;
  case "mi":
    $constant = 3959; // KM
    break;
}

$query = "SELECT store_id, name, address, description, longitude, latitude, 
    (? * acos(cos(radians(?)) * cos( radians(latitude)) * cos(radians(longitude)
     - radians(?)) + sin(radians(?)) * sin(radians(latitude)))) 
    AS distanceFromLocation FROM stores";



$stmt = $mysqli->prepare($query);
$stmt->bind_param($constant, $distance, $user_latitude, $user_longitude, $user_latitude);
etc.

答案 1 :(得分:0)

如果您必须使用MySQL进行地理空间工作,请不要自行重新实现公式,请查看the geospatial support。根据{{​​3}},这应该没问题。除此之外,您可以查看st_distance_sphere或st_distance_spheroid,两者都是the performance blog, mysql supports st_distance for determining distance between two points