Fastest Way to Find Distance Between Two Lat/Long Points

后端 未结 15 1233
时光说笑
时光说笑 2020-11-21 10:12

I currently have just under a million locations in a mysql database all with longitude and latitude information.

I am trying to find the distance between one point a

15条回答
  •  不要未来只要你来
    2020-11-21 10:31

    The following MySQL function was posted on this blog post. I haven't tested it much, but from what I gathered from the post, if your latitude and longitude fields are indexed, this may work well for you:

    DELIMITER $$
    
    DROP FUNCTION IF EXISTS `get_distance_in_miles_between_geo_locations` $$
    CREATE FUNCTION get_distance_in_miles_between_geo_locations(
      geo1_latitude decimal(10,6), geo1_longitude decimal(10,6), 
      geo2_latitude decimal(10,6), geo2_longitude decimal(10,6)) 
    returns decimal(10,3) DETERMINISTIC
    BEGIN
      return ((ACOS(SIN(geo1_latitude * PI() / 180) * SIN(geo2_latitude * PI() / 180) 
        + COS(geo1_latitude * PI() / 180) * COS(geo2_latitude * PI() / 180) 
        * COS((geo1_longitude - geo2_longitude) * PI() / 180)) * 180 / PI()) 
        * 60 * 1.1515);
    END $$
    
    DELIMITER ;
    

    Sample usage:

    Assuming a table called places with fields latitude & longitude:

    SELECT get_distance_in_miles_between_geo_locations(-34.017330, 22.809500,
    latitude, longitude) AS distance_from_input FROM places;
    

提交回复
热议问题