Sorting MySQL query by Latitude/Longitude

前端 未结 5 1437
刺人心
刺人心 2020-12-14 04:13

Every user in my database has their latitude and longitude stored in two fields (lat, lon)

The format of each field is:

lon | -1.403976 
lat | 53.428         


        
5条回答
  •  我在风中等你
    2020-12-14 04:23

    This is the formula that gave me the correct results (as opposed to the solutions above). Confirmed by using the Google Maps "Measure distance" feature (direct distance, not the transportation distance).

    SELECT
        *,
        ( 3959 * acos( cos( radians(:latitude) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(:longitude) ) + sin( radians(:latitude) ) * sin( radians( latitude ) ) ) ) AS `distance`
    FROM `locations`
    ORDER BY `distance` ASC
    

    :latitude and :longitude are the placeholders for the PDO functions. You can replace them with the actual values if you'd like. latitude and longitude are the column names.

    3959 is the Earth radius in miles; the distance output will be in miles as well. To change it to kilometers, replace 3959 with 6371.

提交回复
热议问题