select within 20 kilometers based on latitude/longitude

后端 未结 4 1023
野性不改
野性不改 2020-12-02 13:53

i have a mysql table structured as per the example below:

POSTAL_CODE_ID|PostalCode|City|Province|ProvinceCode|CityType|Latitude|Longitude
7|A0N 2J0|Ramea|Ne         


        
4条回答
  •  一生所求
    2020-12-02 14:24

    You simply take your haversine formula and apply it like this:

    SELECT   *,
             6371 * ACOS(SIN(RADIANS( $lat1 )) * SIN(RADIANS(`Latitude`)) +
             COS(RADIANS( $lat1 )) * COS(RADIANS(`Latitude`)) * COS(RADIANS(`Longitude`) -
             RADIANS( $lon1 ))) AS `distance`
    FROM     `table`
    WHERE    `distance` <= 20
    ORDER BY `distance` ASC
    

    Replace $lat1 and $lon1 with the latitude and longitude you want to compare against.

提交回复
热议问题