I found some good suggestions here to find nearest locations with a pair of single latitude and longitude. But i am looking for an efficient way to find the nearest locations with a set of (multiple) pairs of latitudes and longitudes. And then group the results. I can use UNION in mysql with the query i have written below. But i am looking for way to do it without UNION. My table (user_locations)
+----+--------+-----------+-----------+-----------------------------+
| id | userid | lat | lng | point |
+----+--------+-----------+-----------+-----------------------------+
| 1 | 18 | 48.204784 | 16.369640 | POINT(16.369640, 48.204784) |
+----+--------+-----------+-----------+-----------------------------+
| 2 | 21 | 48.205872 | 16.368946 | POINT(16.368946, 48.205872) |
+----+--------+-----------+-----------+-----------------------------+
| 3 | 11 | 48.205914 | 16.367867 | POINT(16.367867, 48.205914) |
+----+--------+-----------+-----------+-----------------------------+
The query with single lat and lng pair: Find the users who are near [48.205546, 16.368667]
SELECT
name,
( 3959 * acos( cos( radians(48.205546) ) * cos( radians( locations.lat ) )
* cos( radians(locations.lng) - radians(16.368667)) + sin(radians(48.205546))
* sin( radians(locations.lat)))) AS distance
FROM user_locations
WHERE active = 1
HAVING distance < 10
ORDER BY distance;
I am looking to use the above query with a set of given lat longs: Find the users who are near: [[48.205546, 16.368667], [48.205084, 16.369712], [48.205660, 16.367947]]
SELECT
name,
( 3959 * acos( cos( radians($lat1,$lat2,$lat3,$lat4) ) * cos( radians( locations.lat ) )
* cos( radians(locations.lng) - radians($lng1,$lng2,$lng3,$lng4)) + sin(radians($lat))
* sin( radians(locations.lat)))) AS distance
FROM user_locations
WHERE active = 1
HAVING distance < 10
ORDER BY distance;
I am not really looking for the specific output because the results will be grouped so distance is not really that important. User 18 could be near to multiple lat lng pairs. Grouping the results with userid will retrieve only one row of userid: 18.
+----+--------+-----------+-----------+-----------------------------+--+
| id | userid | lat | lng | point | |
+----+--------+-----------+-----------+-----------------------------+--+
| 2 | 21 | 48.205872 | 16.368946 | POINT(16.368946, 48.205872) | |
+----+--------+-----------+-----------+-----------------------------+--+
| 3 | 11 | 48.205914 | 16.367867 | POINT(16.367867, 48.205914) | |
+----+--------+-----------+-----------+-----------------------------+--+