I have a list of points (actually shops coordinates) and I need to determine if they lay within certain boundaries.
In C# I know how to create a point from lat&lng
var point = new GeoCoordinate(latitude, longitude);
But how can I check if that point is contained in the rectangle defined by those other two points:
var swPoint = new GeoCoordinate(bounds.swlat, bounds.swlng);
var nePoint = new GeoCoordinate(bounds.nelat, bounds.nelng);
Is there any class method I can use?
Approach: If we observe carefully, It will be clear that for a point to be lie inside the rectangle, it should be lie inside the x-coordinate (x1, x2) of the rectangle as well as it should also lie inside the y-coordinate (y1, y2) of the rectangle.
The point will be inside a convex polygon if and only if it lies on the same side of the support line of each of the segments. That is, either it lies on the left of every line or it lines on the right of every line.
The simplest way to determine if a point lies inside a triangle is to check the number of points in the convex hull of the vertices of the triangle adjoined with the point in question. If the hull has three points, the point lies in the triangle's interior; if it is four, it lies outside the triangle.
If you are using http://msdn.microsoft.com/en-us/library/system.device.location.geocoordinate.aspx
You will have to write your own method to make this check. You may want to make it an extension method (Lot's of resources available on Extension Methods online.)
Then it is almost as simple as
public static Boolean isWithin(this GeoCoordinate pt, GeoCoordinate sw, GeoCoordinate ne)
{
return pt.Latitude >= sw.Latitude &&
pt.Latitude <= ne.Latitude &&
pt.Longitude >= sw.Longitude &&
pt.Longitude <= ne.Longitude
}
There is one corner case to consider. The above method will fail if the box defined by sw, ne crosses the 180-degree Longitude. So additional code will have to be written to cover that case, thus slowing the performance of the method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With