find_closest_point

pyhelpers.geom.find_closest_point(pt, ref_pts, as_geom=True)

Find the closest point of the given point to a list of points.

Parameters
  • pt (tuple or list or shapely.geometry.Point) – (longitude, latitude)

  • ref_pts (Iterable or numpy.ndarray or list or tuple or shapely.geometry.Point or shapely.geometry.MultiPoint or shapely.geometry.LineString or shapely.geometry.MultiLineString or shapely.geometry.Polygon or shapely.geometry.MultiPolygon or shapely.geometry.GeometryCollection) – a sequence of reference (tuple/list of length 2) points

  • as_geom (bool) – whether to return shapely.geometry.Point, defaults to True

Returns

the point closest to pt

Return type

shapely.geometry.Point or 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])