1

我正在开发一个网站,该网站将显示离特定位置最近的商店位置。我正在使用半正弦公式来确定距离,除了 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,它将返回正确的距离值。任何想法为什么我无法访问距离场?是因为它是一个计算字段吗?

4

2 回答 2

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.
于 2014-01-03T11:00:03.070 回答
0

如果您必须使用MySQL进行地理空间工作,而不是自己重新实现公式,请查看地理空间支持。根据性能博客,mysql支持 st_distance 来确定两点之间的距离,这应该没问题。除此之外,您可以查看 st_distance_sphere 或 st_distance_spheroid,从5.1 开始支持这两者。

于 2014-01-02T20:21:04.827 回答