MySQL Great Circle Distance (Haversine formula)

前端 未结 9 1381
栀梦
栀梦 2020-11-21 06:53

I\'ve got a working PHP script that gets Longitude and Latitude values and then inputs them into a MySQL query. I\'d like to make it solely MySQL. Here\'s my current PHP Cod

9条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 07:08

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

    with latitude and longitude in radian.

    so

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

    is your SQL query

    to get your results in Km or miles, multiply the result with the mean radius of Earth (3959 miles,6371 Km or 3440 nautical miles)

    The thing you are calculating in your example is a bounding box. If you put your coordinate data in a spatial enabled MySQL column, you can use MySQL's build in functionality to query the data.

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

提交回复
热议问题