Many apps now have a "people nearby" feature.
In a cursory way, the user will tell the server when they log in, and the server will log a list of the user's location information.
Assuming that there are only 10 people in the server, it is very simple to find the people nearby, just write a function that calculates the distance, and then go through the list of locations with a length of 10, from near to far, to return the sorted list.
So what if there are 10 million people in the server, or hundreds of millions of people, like. It is not appropriate to traverse from beginning to end (the complexity O (n)).
Typically, a "quad tree" is used to build these large numbers of location information.
1. Four Fork Tree
As the name implies, Quadtree is a tree structure with a maximum of 4 leaf nodes.
2. Geographical location and four fork tree
Defines a global location as a rectangle, using two-dimensional data in longitude and latitude to locate points worldwide.
Longitude range [ -90,90], Latitude range [-180,180].
When the number of logged-in servers is increasing, more than one agreed value, the rectangle is split into 4 smaller rectangles, distributing the position information into smaller rectangles (such as the Pacific, Atlantic, etc.)
Smaller rectangles store information that is more than the agreed value, and then split.
3. Find a nearby point
Suppose I am in the Library of China Agriculture in Tianhe, Guangzhou, want to find the location of 10 people nearby.
So first we need to traverse from the root node (global) to the Tianhe District node, and there are no more than 10 people in the list to search for this node.
If there are not enough 10 people, then the top level of the Guangzhou node request, may find the remaining people in the Haizhu District.
Quad Tree Search for people nearby