MySQL大圆距离(Haversine公式)


184

我有一个工作的PHP脚本,该脚本获取经度和纬度值,然后将它们输入到MySQL查询中。我只想将其制作成MySQL。这是我当前的PHP代码:

if ($distance != "Any" && $customer_zip != "") { //get the great circle distance

    //get the origin zip code info
    $zip_sql = "SELECT * FROM zip_code WHERE zip_code = '$customer_zip'";
    $result = mysql_query($zip_sql);
    $row = mysql_fetch_array($result);
    $origin_lat = $row['lat'];
    $origin_lon = $row['lon'];

    //get the range
    $lat_range = $distance/69.172;
    $lon_range = abs($distance/(cos($details[0]) * 69.172));
    $min_lat = number_format($origin_lat - $lat_range, "4", ".", "");
    $max_lat = number_format($origin_lat + $lat_range, "4", ".", "");
    $min_lon = number_format($origin_lon - $lon_range, "4", ".", "");
    $max_lon = number_format($origin_lon + $lon_range, "4", ".", "");
    $sql .= "lat BETWEEN '$min_lat' AND '$max_lat' AND lon BETWEEN '$min_lon' AND '$max_lon' AND ";
    }

有谁知道如何完全使用MySQL?我浏览了一下互联网,但是关于它的大多数文献都令人困惑。


4
根据以下所有出色的答案,以下是有效的Haversine公式的工作示例
StartupGuy 2014年

感谢您分享Michael.M
Nick Woodhams 2014年

stackoverflow.com/a/40272394/1281385 有一个如何确保命中索引的示例
exussum

Answers:


357

Google Code常见问题解答-使用PHP,MySQL和Google Maps创建商店定位器

这是一条SQL语句,它将找到距离37,-122坐标25英里范围内的最近20个位置。它根据该行的纬度/经度和目标纬度/经度计算距离,然后仅询问距离值小于25的行,按距离对整个查询进行排序,并将其限制为20个结果。要按公里而不是英里进行搜索,请将3959替换为6371。

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;

2
sql语句真的很好。但是我在哪里可以将我的坐标传递给该语句?我看不到坐标已通过的任何地方
Mann

32
用您的坐标替换37和-122。
帕维尔·楚楚瓦

5
我想知道如果有数百万个地点(+数以千计的访客),会对性能产生影响……
HalilÖzgür

12
您可以按照本文档中的说明缩小查询范围,以获得更好的性能:tr.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL
maliayas 2012年

2
@FosAvance是的,如果您的markers表具有id,lan和lng字段,则此查询有效。
Pavel Chuchuva 2014年

32

$greatCircleDistance = acos( cos($latitude0) * cos($latitude1) * cos($longitude0 - $longitude1) + sin($latitude0) * sin($latitude1));

纬度和经度的弧度

所以

SELECT 
  acos( 
      cos(radians( $latitude0 ))
    * cos(radians( $latitude1 ))
    * cos(radians( $longitude0 ) - radians( $longitude1 ))
    + sin(radians( $latitude0 )) 
    * sin(radians( $latitude1 ))
  ) AS greatCircleDistance 
 FROM yourTable;

是您的SQL查询

要获得以公里或英里为单位的结果,请将结果乘以地球的平均半径(3959英里,6371公里或3440海里)

您在示例中计算的是一个边界框。如果将坐标数据放在已启用空间的MySQL列中,则可以使用MySQL的内置功能来查询数据。

SELECT 
  id
FROM spatialEnabledTable
WHERE 
  MBRWithin(ogc_point, GeomFromText('Polygon((0 0,0 3,3 3,3 0,0 0))'))

13

如果将辅助字段添加到坐标表,则可以缩短查询的响应时间。

像这样:

CREATE TABLE `Coordinates` (
`id` INT(10) UNSIGNED NOT NULL COMMENT 'id for the object',
`type` TINYINT(4) UNSIGNED NOT NULL DEFAULT '0' COMMENT 'type',
`sin_lat` FLOAT NOT NULL COMMENT 'sin(lat) in radians',
`cos_cos` FLOAT NOT NULL COMMENT 'cos(lat)*cos(lon) in radians',
`cos_sin` FLOAT NOT NULL COMMENT 'cos(lat)*sin(lon) in radians',
`lat` FLOAT NOT NULL COMMENT 'latitude in degrees',
`lon` FLOAT NOT NULL COMMENT 'longitude in degrees',
INDEX `lat_lon_idx` (`lat`, `lon`)
)    

如果您使用的是TokuDB,则可以在两个谓词上添加聚簇索引,从而获得更好的性能,例如:

alter table Coordinates add clustering index c_lat(lat);
alter table Coordinates add clustering index c_lon(lon);

对于每个点,您将需要基本的经度和纬度,以及以弧度为单位的sin(lat),以弧度为单位的cos(lat)* cos(lon)和以弧度为单位的cos(lat)* sin(lon)。然后创建一个mysql函数,如下所示:

CREATE FUNCTION `geodistance`(`sin_lat1` FLOAT,
                              `cos_cos1` FLOAT, `cos_sin1` FLOAT,
                              `sin_lat2` FLOAT,
                              `cos_cos2` FLOAT, `cos_sin2` FLOAT)
    RETURNS float
    LANGUAGE SQL
    DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY INVOKER
   BEGIN
   RETURN acos(sin_lat1*sin_lat2 + cos_cos1*cos_cos2 + cos_sin1*cos_sin2);
   END

这给了你距离。

不要忘记在纬度/经度上添加索引,以便包围盒可以帮助搜索而不是减慢搜索速度(该索引已添加到上面的CREATE TABLE查询中)。

INDEX `lat_lon_idx` (`lat`, `lon`)

给定一个只有纬度/经度坐标的旧表,您可以设置一个脚本来更新它,如下所示:(使用meekrodb的php)

$users = DB::query('SELECT id,lat,lon FROM Old_Coordinates');

foreach ($users as $user)
{
  $lat_rad = deg2rad($user['lat']);
  $lon_rad = deg2rad($user['lon']);

  DB::replace('Coordinates', array(
    'object_id' => $user['id'],
    'object_type' => 0,
    'sin_lat' => sin($lat_rad),
    'cos_cos' => cos($lat_rad)*cos($lon_rad),
    'cos_sin' => cos($lat_rad)*sin($lon_rad),
    'lat' => $user['lat'],
    'lon' => $user['lon']
  ));
}

然后,您可以优化实际查询以仅在真正需要时执行距离计算,例如通过从内部和外部定界圆形(井,椭圆形)。为此,您需要为查询本身预先计算几个指标:

// assuming the search center coordinates are $lat and $lon in degrees
// and radius in km is given in $distance
$lat_rad = deg2rad($lat);
$lon_rad = deg2rad($lon);
$R = 6371; // earth's radius, km
$distance_rad = $distance/$R;
$distance_rad_plus = $distance_rad * 1.06; // ovality error for outer bounding box
$dist_deg_lat = rad2deg($distance_rad_plus); //outer bounding box
$dist_deg_lon = rad2deg($distance_rad_plus/cos(deg2rad($lat)));
$dist_deg_lat_small = rad2deg($distance_rad/sqrt(2)); //inner bounding box
$dist_deg_lon_small = rad2deg($distance_rad/cos(deg2rad($lat))/sqrt(2));

在进行了这些准备之后,查询将如下所示(php):

$neighbors = DB::query("SELECT id, type, lat, lon,
       geodistance(sin_lat,cos_cos,cos_sin,%d,%d,%d) as distance
       FROM Coordinates WHERE
       lat BETWEEN %d AND %d AND lon BETWEEN %d AND %d
       HAVING (lat BETWEEN %d AND %d AND lon BETWEEN %d AND %d) OR distance <= %d",
  // center radian values: sin_lat, cos_cos, cos_sin
       sin($lat_rad),cos($lat_rad)*cos($lon_rad),cos($lat_rad)*sin($lon_rad),
  // min_lat, max_lat, min_lon, max_lon for the outside box
       $lat-$dist_deg_lat,$lat+$dist_deg_lat,
       $lon-$dist_deg_lon,$lon+$dist_deg_lon,
  // min_lat, max_lat, min_lon, max_lon for the inside box
       $lat-$dist_deg_lat_small,$lat+$dist_deg_lat_small,
       $lon-$dist_deg_lon_small,$lon+$dist_deg_lon_small,
  // distance in radians
       $distance_rad);

上面的查询中的EXPLAIN可能表示它没有使用索引,除非有足够的结果触发该索引。当坐标表中有足够的数据时,将使用索引。您可以将FORCE INDEX(lat_lon_idx)添加到SELECT,以使其不考虑表大小而使用索引,因此可以通过EXPLAIN验证其是否正常工作。

使用上面的代码示例,您应该可以有效地并且按距离进行对象搜索并且可扩展,并且误差最小。


10

我必须对此进行一些详细的说明,所以我将分享我的结果。这使用zip带有latitudelongitude表的表。它不依赖于Google地图。相反,您可以将其调整为包含经/纬度的任何表。

SELECT zip, primary_city, 
       latitude, longitude, distance_in_mi
  FROM (
SELECT zip, primary_city, latitude, longitude,r,
       (3963.17 * ACOS(COS(RADIANS(latpoint)) 
                 * COS(RADIANS(latitude)) 
                 * COS(RADIANS(longpoint) - RADIANS(longitude)) 
                 + SIN(RADIANS(latpoint)) 
                 * SIN(RADIANS(latitude)))) AS distance_in_mi
 FROM zip
 JOIN (
        SELECT  42.81  AS latpoint,  -70.81 AS longpoint, 50.0 AS r
   ) AS p 
 WHERE latitude  
  BETWEEN latpoint  - (r / 69) 
      AND latpoint  + (r / 69)
   AND longitude 
  BETWEEN longpoint - (r / (69 * COS(RADIANS(latpoint))))
      AND longpoint + (r / (69 * COS(RADIANS(latpoint))))
  ) d
 WHERE distance_in_mi <= r
 ORDER BY distance_in_mi
 LIMIT 30

查看该查询中间的这一行:

    SELECT  42.81  AS latpoint,  -70.81 AS longpoint, 50.0 AS r

zip将在纬度/经度42.81 / -70.81的50.0英里内搜索表中的30个最接近的条目。当您将其构建到应用程序中时,就可以在其中放置自己的点和搜索半径。

如果要以公里而不是英里为单位,请在查询中更改69为,111.045然后更改3963.176378.10

这是详细的文章。希望对您有所帮助。 http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/


3

我编写了一个可以计算出相同值的过程,但是您必须在相应的表中输入纬度和经度。

drop procedure if exists select_lattitude_longitude;

delimiter //

create procedure select_lattitude_longitude(In CityName1 varchar(20) , In CityName2 varchar(20))

begin

    declare origin_lat float(10,2);
    declare origin_long float(10,2);

    declare dest_lat float(10,2);
    declare dest_long float(10,2);

    if CityName1  Not In (select Name from City_lat_lon) OR CityName2  Not In (select Name from City_lat_lon) then 

        select 'The Name Not Exist or Not Valid Please Check the Names given by you' as Message;

    else

        select lattitude into  origin_lat from City_lat_lon where Name=CityName1;

        select longitude into  origin_long  from City_lat_lon where Name=CityName1;

        select lattitude into  dest_lat from City_lat_lon where Name=CityName2;

        select longitude into  dest_long  from City_lat_lon where Name=CityName2;

        select origin_lat as CityName1_lattitude,
               origin_long as CityName1_longitude,
               dest_lat as CityName2_lattitude,
               dest_long as CityName2_longitude;

        SELECT 3956 * 2 * ASIN(SQRT( POWER(SIN((origin_lat - dest_lat) * pi()/180 / 2), 2) + COS(origin_lat * pi()/180) * COS(dest_lat * pi()/180) * POWER(SIN((origin_long-dest_long) * pi()/180 / 2), 2) )) * 1.609344 as Distance_In_Kms ;

    end if;

end ;

//

delimiter ;

3

我无法评论以上答案,但请谨慎使用@Pavel Chuchuva的答案。如果两个坐标相同,则该公式将不会返回结果。在这种情况下,distance为null,因此该行将不会按原样返回该公式。

我不是MySQL专家,但这似乎对我有用:

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 OR distance IS NULL ORDER BY distance LIMIT 0 , 20;

2
如果位置相同,则不应得出NULL,而应为零(等于ACOS(1)0)。您可能会看到xaxis * xaxis + yaxis * yaxis + zaxis * zaxis超出了ACOS的舍入问题,但是您似乎并没有对此进行防范?
罗兰·肖

3
 SELECT *, (  
    6371 * acos(cos(radians(search_lat)) * cos(radians(lat) ) *   
cos(radians(lng) - radians(search_lng)) + sin(radians(search_lat)) *         sin(radians(lat)))  
) AS distance  
FROM table  
WHERE lat != search_lat AND lng != search_lng AND distance < 25  
 ORDER BY distance  
FETCH 10 ONLY 

25公里的距离


最后一个(弧度(纬度)必须为sin(弧度(纬度)))
公斤

即时通讯收到错误“未知列距离”,这是为什么?
吉尔·约翰

@JillJohn如果您只想要距离,则可以按距离完全删除订单。如果要对结果进行排序,可以使用-ORDER BY(6371 * acos(cos(radians(search_lat))* cos(radians(lat))* cos(radians(lng)-radians(search_lng))+ sin(radians (search_lat))* sin(radians(lat))))。
哈里斯·拉尔瓦尼

2

我认为我的javascript实现可以很好地参考:

/*
 * Check to see if the second coord is within the precision ( meters )
 * of the first coord and return accordingly
 */
function checkWithinBound(coord_one, coord_two, precision) {
    var distance = 3959000 * Math.acos( 
        Math.cos( degree_to_radian( coord_two.lat ) ) * 
        Math.cos( degree_to_radian( coord_one.lat ) ) * 
        Math.cos( 
            degree_to_radian( coord_one.lng ) - degree_to_radian( coord_two.lng ) 
        ) +
        Math.sin( degree_to_radian( coord_two.lat ) ) * 
        Math.sin( degree_to_radian( coord_one.lat ) ) 
    );
    return distance <= precision;
}

/**
 * Get radian from given degree
 */
function degree_to_radian(degree) {
    return degree * (Math.PI / 180);
}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.