Search code examples
c#mapscoordinates

How to find if a GeoCoordinate point is within boundaries


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?


Solution

  • 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.