问题
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