Given a user's location, select rows that include that user in their radius

邮差的信 提交于 2019-12-31 07:03:16

问题


I have a MySQL table with rows latitude, longitude and radius. Latitude and longitude are of type DOUBLE; radius is of type INT and measured in meters. Essentially, each row represents a circle on Earth.

Given values of user_latitude and user_longitude, how can I select all the rows that include the user in their circles?

I made a quick diagram to illustrate in case my question wasn't clear. Each red dot represents a user_latitude and user_longitude point, each circle represents a latitude, longitude and radius row in the database.


回答1:


step1: implement haversine distance formula

delimiter //
create function DistanceInKm(
        lat1 FLOAT, lon1 FLOAT,
        lat2 FLOAT, lon2 FLOAT
     ) returns float
    NO SQL DETERMINISTIC
begin
    return degrees(acos(
              cos(radians(lat1)) *
              cos(radians(lat2)) *
              cos(radians(lon2) - radians(lon1)) +
              sin(radians(lat1)) * sin(radians(lat2))
            )) * 111.045;
END//
delimiter ;

(the magic number 111.045 converts it to km, use 69 for miles)

step 2: use the function

select * from areas where distance(lat, long, USERLAT, USERLONG) < radius

reference



来源:https://stackoverflow.com/questions/29820927/given-a-users-location-select-rows-that-include-that-user-in-their-radius

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!