Given a geometry or envelop, how do we calculate the overlap percentage with different geometries in a shapefile?

Topics: Algorithms, Data Access, General Topics, SharpMap Project
Sep 28, 2014 at 7:18 AM
I have a geometry (say a square) and a shapefile. I would like to calculate the percentage overlap between different geometries/Objects in a shapefile.

I would expect an answer like

Objectid = 1, PercentOverlap = 0%
Objectid = 2, PercentOverlap = 10%
Objectid = 3, PercentOverlap = 30%
Objectid = 4, PercentOverlap = 20%
Objectid = 5, PercentOverlap = 60%
Objectid = 6, PercentOverlap = 0%
Objectid = 7, PercentOverlap = 0%
Objectid = 8, PercentOverlap = 0%
Coordinator
Sep 29, 2014 at 8:51 AM
This should do:
public void OverlapPercentage(string pathToShapeFile, GeoAPI.Geometries.Envelope square, System.IO.TextWriter writer)
{
    var p = new SharpMap.Data.Providers.ShapeFile(pathToShapeFile);
    var g = SharpMap.CoordinateSystems.CoordinateSystemExtensions.GetFactory(p).ToGeometry(square);
    var pg = NetTopologySuite.Geometries.Prepared.PreparedGeometryFactory.Prepare(g);
    var fds = new SharpMap.Data.FeatureDataSet();
    p.ExecuteIntersectionQuery(p.GetExtents(), fds);
    var fdt = fds.Tables[0];
    for (var i = 0; i < fdt.Count; i++)
    {
        var fdr = (SharpMap.Data.FeatureDataRow) fdt.Rows[i];
        if (pg.Intersects(fdr.Geometry))
        {
            var ig = g.Intersection(fdr.Geometry);
            writer.WriteLine("{0};{1:P}", i+1, ig.Area/g.Area);
        }
        else
        {
            writer.WriteLine("{0};{1:P}", i + 1, 0);
        }
    }
}