Python – Get Distance Between Point and Nearest Polygon Using Python and GDAL

distancegdalpolygonpythonshapefile

I want to be able to compute the distance between a point and the nearest polygon from a shapefile. To be more specific, I have some point coordinates and I want to find their distance from a worldwide coastline polygon shapefile. And I have to do that with GDAL in python.

Could you point me to some direction? I have seen a lot of answers, but since I am a novice on GDAL I get more confused every time.

Best Answer

So, after many hours of searching the web for an answer I managed to come up with the following code.

def get_distance_to_coast(x, y, geo_ls, coastf, epsg):

    # Load coastline polygon shapefile
    file = ogr.Open(coastf)
    layer = file.GetLayer(0)

    # Create point geometry
    pt = ogr.Geometry(ogr.wkbPoint)
    pt.AddPoint(x, y)

    polygon = layer.GetFeature(0).GetGeometryRef()

    # Reproject point to shapefile's srs
    src = osr.SpatialReference()
    src.ImportFromEPSG(int(epsg))
    trgt = osr.SpatialReference()
    trgt.ImportFromEPSG(4326)

    transform = osr.CoordinateTransformation(src, trgt)
    pt.Transform(transform)

    # Check for intersection and distance from the closest edge
    if pt.Intersection(polygon).ExportToWkt() == 'GEOMETRYCOLLECTION EMPTY' and pt.Distance(polygon) > 100:
        geo_ls.append([x, y])
        stat = True
    else:
        stat = False

    return stat