# Finding closest distance from point to polygon border using Python

I want to measure the distance of a point(lat,long) to a the border of a Polygon. So I have created the polygon with the coordinates.

``````from shapely.geometry import Polygon, Point

pol = Polygon(zip(lon_list, lat_list))
pol.exterior.distance(some_point)
``````

This gives me some value but no idea what it actually tells me (meters??). Any advice on how to get this?

Any advice on how to calculate the distance from a point to the border of a polygon in Python properly? Getting the closest point of the border from the starting point would also be more than enough.

• You have properly computed the distance from the point to the polygon's border. The unit of the result is the same as the unit of the your coordinates (it calculates the distance in a cartesian plane). So in your case in degrees. If you want the result in meters, you first need to reproject your data to a different coordinate reference system. Commented Oct 14, 2019 at 16:02
• The projection is for sure an issue. but I can calc proper distances with haversine. bigger problem is, how to get the closest point on the border line? I can go through all the points of the polygon but how to find the coordinate... Commented Oct 15, 2019 at 11:44
• Shapely can do that for you shapely.readthedocs.io/en/stable/manual.html#object.project Commented Oct 15, 2019 at 18:43

You can use shapely.ops.nearest_points

Returns a tuple of the nearest points in the input geometries. The points are returned in the same order as the input geometries.

If you have many polygons you can sjoin_nearest each polygon to the points. I only have one:

``````import geopandas as gpd
import shapely

#Create a polygon df with one row
polygon_wkt = r'Polygon ((4.68817446043166264 25.336443345323719, 5.96762589928058151 25.83217176258990477, 7.03666502143541095 24.97199852227128147, 6.82625270474132062 23.6160968646864724, 5.54680126589240086 23.12036844742028663, 4.47776214373757142 23.98054168773890993, 4.68817446043166264 25.336443345323719))'
polydf = gpd.GeoDataFrame(geometry=polygon_geometry, crs=4326)

#Create a point df with some random points inside the polygon
point_geometries = list(polydf.sample_points(size=20).iloc[0].geoms)
pointdf = gpd.GeoDataFrame(geometry=point_geometries, crs=4326)

#For each point, find the nearest point on the polygon border using shapely.ops.nearest_points
pointdf["nearest_polypoint"]= pointdf.geometry.apply(
lambda x: shapely.ops.nearest_points(g1=x, g2=polydf.iloc[0].geometry.boundary)[1])