【问题标题】:Google Sql Query for finding nearest locations not working用于查找最近位置的 Google Sql 查询不起作用
【发布时间】:2017-05-16 16:10:25
【问题描述】:

我正在尝试使用带有 MySQL 的 google geocode API 找到最近的地方,但它显示所有行的距离相同,不知道为什么我在 google provided code 中也遵循相同的步骤

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) )
  * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) 
  * sin( radians( lat ) ) ) ) AS distance
FROM markers
HAVING distance < 25
ORDER BY distance LIMIT 0 , 20;

我发现了这个问题,这个解决方案对我有用https://github.com/rugbyprof/5443-Spatial-Database/blob/master/Mysql_Haversine_Distance.md

【问题讨论】:

  • 要获得距离,您需要两个纬度和两个经度 - 起点和终点。其中一个点是硬编码的吗?
  • “不起作用”是什么意思?请明确点。你看到了什么错误?
  • 我的第一个问题呢?
  • 如果两个地方之间的距离是 4 公里,那么它在所有行中显示 31 公里.. 你可以按照相同的步骤检查它

标签: mysql google-places-api google-geocoder


【解决方案1】:

这是一个 MySQL 函数,它将采用两个纬度/经度对,并为您提供两点之间的度数距离。 它使用Haversine 公式来计算距离。由于地球不是一个完美的球体,因此在靠近 两极和赤道。

  • 要转换为英里,请乘以 3961。
  • 要转换为公里,请乘以 6373。
  • 要转换为米,请乘以 6373000。
  • 要转换为英尺,请乘以 (3961 * 5280) 20914080。

SQL函数:

DELIMITER $$

CREATE FUNCTION `haversine`(
        lat1 FLOAT, lon1 FLOAT,
        lat2 FLOAT, lon2 FLOAT
     ) RETURNS float
    NO SQL
    DETERMINISTIC
    COMMENT 'Returns the distance in degrees on the Earth between two known points of latitude and longitude. To get miles, multiply by 3961, and km by 6373'
BEGIN
    RETURN DEGREES(ACOS(
              COS(RADIANS(lat1)) *
              COS(RADIANS(lat2)) *
              COS(RADIANS(lon2) - RADIANS(lon1)) +
              SIN(RADIANS(lat1)) * SIN(RADIANS(lat2))
            ));
END;
$$

DELIMITER ;

在地址表中添加类型为 FLOAT(10,6) 的纬度和经度列。 编写一个 php 脚本来查找保存记录时的纬度/经度。

然后您可以对表格进行选择以获取带有距离的地址列表。你甚至可以排序 按距离计算结果,或将结果限制在距参考位置一定半径内。

SELECT 
    `street`,
    `city`,
    `state`,
    `zip`,
    (haversine($ref_location_lat,$ref_location_long,`lat`,`long) * 3961) as `distance`
FROM `address_table`
WHERE (haversine($ref_location_lat,$ref_location_long,`lat`,`long) * 3961) < 300    //  Example for limiting returned records to a raduis of 300 miles.
ORDER BY haversine($ref_location_lat,$ref_location_long,`lat`,`long) DESC;      //  Don't need actual distance for sorting, just relative distance.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多