Nearest Neighbour Analysis¶
One commonly used GIS task is to be able to find the nearest neighbour. For instance, you might have a single Point object representing your home location, and then another set of locations representing e.g. public transport stops. Then, quite typical question is “which of the stops is closest one to my home?” This is a typical nearest neighbour analysis, where the aim is to find the closest geometry to another geometry.
In Python this kind of analysis can be done with shapely function called nearest_points()
that returns a tuple of the nearest points in the input geometrie.
Nearest point using Shapely¶
Let’s start by testing how we can find the nearest Point using the nearest_points()
function of Shapely.
Let’s create an origin Point and a few destination Points and find out the closest destination.
In [1]: from shapely.geometry import Point, MultiPoint
In [2]: from shapely.ops import nearest_points
In [3]: orig = Point(1, 1.67)
In [4]: dest1, dest2, dest3 = Point(0, 1.45), Point(2, 2), Point(0, 2.5)
To be able to find out the closest destination point from the origin, we need to create a MultiPoint object from the destination points.
In [5]: destinations = MultiPoint([dest1, dest2, dest3])
In [6]: print(destinations)
MULTIPOINT (0 1.45, 2 2, 0 2.5)
Okey, now we can see that all the destination points are represented as a single MultiPoint object.
- Now we can find out the nearest destination point by using
nearest_points()
function.
In [7]: nearest_geoms = nearest_points(orig, destinations)
In [8]: near_idx0 = nearest_geoms[0]
In [9]: near_idx1 = nearest_geoms[1]
In [10]: print(nearest_geoms)
(<shapely.geometry.point.Point object at 0x000001C7315DBE10>, <shapely.geometry.point.Point object at 0x000001C731917828>)
In [11]: print(near_idx0)