Get results that fall within marker radiuses from database

For solving this you need to understand equation of circle, which is something like this
For any point (x,y) to fall within circle with center (x1, y1) and radius r units is

(x-x1)^2 + (y - y1)^2 <= r^2

where a^b = a to the power b

Here in your case User B’s (latitude, longitude) are the center of circle, User A’s (latitude, longitude) are the points (x,y) and radius = 2kms.

But basic problem is of changing degrees of latitudes to longitudes, so here is solution, 1 degree = 111.12 km. So to keep units same on both side of equation, we will convert it to Kms

So our final equation becomes:

((x-x1)*111.12)^2 + ((y-y1)*111.12)^2 = 4      (=2^2) 

SQL statement for the same should look something like this

SELECT A.user_id, A.radius_id, A.latitude, A.logitude
FROM UserA AS A, 
     (SELECT user_id, latitude, longitude 
       FROM UserB 
       WHERE user_id = 8) AS B
WHERE (POW((A.latitude-B.latitude)*111.12, 2) + POW((A.longitude - B.longitude)*111.12, 2)) <= 4
/* **Edit** Here I have used (A.longitude - B.longitude)*111.12, for more accurate results one can replace it with (A.longitude - B.longitude)*111.12*cos(A.latitude)) or (A.longitude - B.longitude)*111.12*cos(B.latitude)) 

And, as i have suggested in the comments that first filter some records based on approximation, so whether one uses A.latitude or B.latitude it will not make much difference */

Hope this will help…

Leave a Comment