I am using a shapefile(shp) that has an addition field called "ID". The shapefile is clean and does not have any overlapping polygons. When I pass this shapeFile to the following function, I keep getting inconsistent results. (The Id returned is not always the same for same set of latitude longitude).
public static long? GetIdFromLatLong(IProvider provider, double lat, double lon)
{
var matchingRowIds = new Collection<uint>();
var vertex = new GeoAPI.Geometries.Coordinate(lon, lat);
var ntsPoint = new NetTopologySuite.Geometries.Point(vertex.X, vertex.Y);
var envelop = new GeoAPI.Geometries.Envelope(vertex);
if (!provider.IsOpen)
{
provider.Open();
}
var ids = provider.GetObjectIDsInView(envelop);
foreach (uint id in ids)
{
var geom = provider.GetGeometryByID(id);
if (geom.Contains(ntsPoint))
{
matchingRowIds.Add(id);
}
}
// Get region Id from RowId
var matchedId = matchingRowIds.Count == 0
? null
: matchingRowIds.Select(i => (long?) provider.GetFeature(i)["ID"]).FirstOrDefault(i => i != 0);
return matchedId;
}
I initially suspected that there are multiple polygons that are being matched and the FirstOrDefault is causing me to get different results but that does not seem to be the case either because when I put a breakpoint in this function, I always have only one entry in matchingRowIds.
Am I doing something wrong/Is there a better way to get the polygon that contains a given point from a shapefile?
Note : I am using sharpMap v1.0.4.1