Question

I am working on a website that will show the nearest store locations to a specific location. I am using the haversine formula to determine the distance and everything is working except the XML cannot see the distance field that I have created.

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);
  }
}

The distanceFromLocation variable is always empty when it gets in the the while loop. I have tested the SQL and it will return the correct distance values. Any ideas why I cannot access the distance field? Is it because it is a calculated field?

Was it helpful?

Solution

You need to incorporate the result from switch as the first parameter. I also changed $distance to $constant for clarity.

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.

OTHER TIPS

If you must use MySQL for geospatial work, instead of reimplementing formulae yourself, look at the geospatial support. According to the performance blog, mysql supports st_distance for determining distance between two points, which should be fine. Barring that, you can look into st_distance_sphere or st_distance_spheroid, both of which are supported as of 5.1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top