Sorting MySQL query by Latitude/Longitude

前端 未结 5 1434
刺人心
刺人心 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:36

    Using just SELECT * FROM Table WHERE lat between $minlat and $maxlat will not be accurate enough.

    The correct way to query distance is using the coordinates in radians.

    Here is a handy reference - http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates

    For example:

    And if you want to do the order by and show the distance:

    Edited for @Blazemonger and the avoidance of doubt :) If you want to work in degrees instead of radians:

    You could easily wrap this up into a class that accepted Radians or Degrees from the information provided above.

提交回复
热议问题