0

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.

  • There is a bit of confusion about geometries, GDAL handles the rasters but OGR does the geometries; GDAL and OGR are being integrated into one package but for python I don't think it's fully dissolved yet. First check that that your point isn't inside a polygon with your polygon geometry.Contains(yourPoint) then iterate the rows and find geometry.Distance(yourPoint) keeping the minimum. Have a read of pcjericks.github.io/py-gdalogr-cookbook/… and see if that makes more sense. – Michael Stimson Jun 8 '18 at 12:05
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.