A simple way would be to sort the points along the longitude, and then, when searching for friends, find the minimum and maximum longitude of possible matches. Sorting the list is O (n log n), and searching for friends is linear, but only for friends in the longitude range. Here is an example for the case when you have all the points on a flat two-dimensional surface:
# friends is the sorted list of (x, y) tuples, (px, py) is my location def get_near(friends, px, py, maxdist): i1 = bisect.bisect_left(friends, (px - maxdist, py)) i2 = bisect.bisect_right(friends, (px + maxdist, py)) return [(x, y) for (x, y) in friends[i1:i2] if math.hypot(px - x, py - y) < maxdist]
For the case of longitude / latitude, you will need to use another function to check the distance instead of the Euclidean distance (math.hypot).
source share