find_closest_point¶
- pyhelpers.geom.find_closest_point(pt, ref_pts, as_geom=True)[source]¶
Find the closest point in a sequence of reference points to a given point.
This function calculates and returns the point closest to
pt
from a sequence of reference pointsref_pts
. The closest point can be returned either as a Shapely Point geometry (shapely.geometry.Point) or as a numpy.ndarray.- Parameters:
pt (tuple | list | shapely.geometry.Point) – Point for which the closest point is to be found.
ref_pts (Iterable | numpy.ndarray | list | tuple | shapely.geometry.base.BaseGeometry) – Sequence of reference points to search for the closest point.
as_geom (bool) – Whether to return the closest point as a shapely.geometry.Point; defaults to
True
.
- Returns:
Closest point to
pt
fromref_pts
.- Return type:
shapely.geometry.Point | numpy.ndarray
Examples:
>>> from pyhelpers.geom import find_closest_point >>> from pyhelpers._cache import example_dataframe >>> example_df = example_dataframe() >>> example_df Longitude Latitude City London -0.127647 51.507322 Birmingham -1.902691 52.479699 Manchester -2.245115 53.479489 Leeds -1.543794 53.797418 >>> # Find the city closest to London >>> london = example_df.loc['London'].values >>> ref_cities = example_df.loc['Birmingham':, :].values >>> closest_to_london = find_closest_point(pt=london, ref_pts=ref_cities) >>> closest_to_london.wkt # Birmingham 'POINT (-1.9026911 52.4796992)' >>> # Find the city closest to Leeds >>> leeds = example_df.loc['Leeds'].values >>> ref_cities = example_df.loc[:'Manchester', :].values >>> closest_to_leeds = find_closest_point(pt=leeds, ref_pts=ref_cities) >>> closest_to_leeds.wkt # Manchester 'POINT (-2.2451148 53.4794892)' >>> closest_to_leeds = find_closest_point(pt=leeds, ref_pts=ref_cities, as_geom=False) >>> closest_to_leeds # Manchester array([-2.2451148, 53.4794892])