I am using the code to check if a coordinate lies inside a polygon or not, But whenever I test a coordinate that is close to the boundary for e.g 300 meters sometimes it returns true, sometimes false.
Below is the function I am using
public static bool IsPointInPolygon2(SentinelLocation[] polygon,SentinelLocation p)
{
double minX = polygon[0].Longitude;
double maxX = polygon[0].Longitude;
double minY = polygon[0].Latitude;
double maxY = polygon[0].Latitude;
for (int i = 1; i < polygon.Length; i++)
{
SentinelLocation q = polygon[i];
minX = Math.Min(q.Longitude, minX);
maxX = Math.Max(q.Longitude, maxX);
minY = Math.Min(q.Latitude, minY);
maxY = Math.Max(q.Latitude, maxY);
}
if (p.Longitude < minX || p.Longitude > maxX || p.Latitude < minY || p.Latitude > maxY)
{
return false;
}
// https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html
bool inside = false;
for (int i = 0, j = polygon.Length - 1; i < polygon.Length; j = i++)
{
if ((polygon[i].Latitude > p.Latitude) != (polygon[j].Latitude > p.Latitude) &&
p.Longitude < (polygon[j].Longitude - polygon[i].Longitude) * (p.Latitude - polygon[i].Latitude) / (polygon[j].Latitude - polygon[i].Latitude) + polygon[i].Longitude)
{
inside = !inside;
}
}
return inside;
}
This is the test data i am passing
public bool IsInsidePolyGon(double latitude,double longitude)
{
var location = new SentinelLocation
{
Latitude = latitude,
Longitude = longitude,
};
var polygon = new List<SentinelLocation>();
polygon.Add(new SentinelLocation
{
Latitude = 31.82703,
Longitude = 63.23671
});
polygon.Add(new SentinelLocation
{
Latitude = 34.54806,
Longitude = 61.91835
});
polygon.Add(new SentinelLocation
{
Latitude = 35.37638,
Longitude = 67.32363
});
polygon.Add(new SentinelLocation
{
Latitude = 32.71876,
Longitude = 67.19179
});
var toReturn = PolyUtil.IsPointInPolygon2(polygon.ToArray(),location);
return toReturn;
}
Test case on which this fails is Latitude:34.96946 and Longitude 64.66381
My polygon looks like this
Can anyone guide me what's going wrong here?