【问题标题】:passing variable to Haversine formula将变量传递给 Haversine 公式
【发布时间】:2013-02-09 21:12:48
【问题描述】:

使用来自 google 的查询:link

我正在尝试创建位置搜索,返回设定距离内的所有城镇。 我希望人们能够在表格中输入城镇,我的代码找到城镇名称的 lat + long,然后查询我的数据库以返回设定距离内的所有城镇。

首先,我找到输入位置的 lat + long:

    $location = 'farnborough';

    function getlatlang($location) {
    $geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='. urlencode($location) .'&sensor=false');  
    $output= json_decode($geocode);  
    return $output->results[0]->geometry->location; 
    }

    $objlocation = getlatlang($location);  
    $latitude = $objlocation->lat;  
    $longitude = $objlocation->lng;

这很好,我可以回显结果并且值是正确的。

然后使用上面链接中的查询,我尝试:

    $query = "SELECT town, ( 3959 * acos( cos( radians($latitude) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($longitude) ) + sin( radians($latitude) ) * sin( radians( lat ) ) ) ) AS distance FROM uk_postcode_05 HAVING distance < 25 ORDER BY distance ASC LIMIT 0 , 5";
    $result = mysqli_query($mysqli, $query);
    if(!$result){echo('no result returned - query wrong');
    }

但是查询不起作用并且总是触发错误。我在这里做错了什么?

(我的表有列城镇、邮政编码、纬度、经度)

【问题讨论】:

  • 它会产生什么错误?你没有指定。
  • 你检查 $result->error 的内容了吗?做一个 print_r($result)

标签: php mysql api maps


【解决方案1】:

我在这里假设您已将表定义中的列名从 lat、lng 更改为 latitude、longitude。

在没有实际错误信息的情况下,这是最好的猜测:

SELECT
  town,
  (
    3959 * acos(
      cos(
        radians($latitude)
      ) * cos(
        radians(latitude)
      ) * cos(
        radians(longitude) - radians($longitude)
      ) + sin(
        radians($latitude)
      ) * sin(
        radians(latitude)
      )
    )
  ) AS distance
FROM
  uk_postcode_05
HAVING
  distance < 25
ORDER BY
  distance ASC
LIMIT
  0, 5

这应该可以解决问题,因为在您的查询 latlng 中未定义。

【讨论】:

    【解决方案2】:

    问题可能是您使用的是 HAVING 而不是 WHERE,并且您在 HAVING 子句中使用了“距离”,即使它没有定义。试试这个:

    SELECT town, ( 3959 * acos( cos( radians($latitude) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($longitude) ) + sin( radians($latitude) ) * sin( radians( lat ) ) ) ) AS distance FROM uk_postcode_05 WHERE ( 3959 * acos( cos( radians($latitude) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($longitude) ) + sin( radians($latitude) ) * sin( radians( lat ) ) ) ) < 25 ORDER BY distance ASC LIMIT 0 , 5
    

    【讨论】:

    • 距离在选择部分定义。查询顺序错误。
    • @scones,你能详细说明一下吗?
    • 请忽略订单声明。查询的顺序很好。很久没用having
    猜你喜欢
    • 2012-03-03
    • 2023-02-24
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 2018-01-02
    相关资源
    最近更新 更多