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 : from shapely.geometry import Point, MultiPoint In : from shapely.ops import nearest_points In : orig = Point(1, 1.67) In : 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 : destinations = MultiPoint([dest1, dest2, dest3]) In : 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
In : nearest_geoms = nearest_points(orig, destinations) In : near_idx0 = nearest_geoms In : near_idx1 = nearest_geoms In : print(nearest_geoms) (<shapely.geometry.point.Point object at 0x000002A232089C50>, <shapely.geometry.point.Point object at 0x000002A232089860>) In : print(near_idx0)