Richard Friend
Richard Friend

Reputation: 16018

find out if long/lat within rectangle

Given a top-left long/lat and a bottom-right long/lat how can i find out if a given long/lat falls within the rectangle ?

Ideally i would be looking at something like

bool IsWithinArea(float topLeftLat,float topLeftLong,
   float bottomRightLat,float bottomRightLong,float testLat,float testLong)

Update

The one problem is that the rectangle created from the long/lat may be from a rotated map, so bottom right will not always be greater than top left...

Upvotes: 3

Views: 3503

Answers (4)

Snowbear
Snowbear

Reputation: 17274

We can make it more interesting than trivial checks:

return new Rect(topLeftLat, topLeftLong, bottomRightLat - topLeftLat, bottomRightLong - topLeftLong)
      .Contains(testLat, testLong);

P.S.: Rect.Contains(...) method

Upvotes: 5

erlando
erlando

Reputation: 6756

One approach would be to normalize your long/lat pairs to simple x/y coordinates. Then it should be a simple excersize to determine if a point falls within the rectangle.

long/lat to x/y conversion can be found here: Convert Lat/Longs to X/Y Co-ordinates

Upvotes: 1

Ralf de Kleine
Ralf de Kleine

Reputation: 11756

Not sure if I'm thinking to simple

bool IsWithinArea(float topLeftLat, float topLeftLong, float bottomRightLat, float bottomRightLong, float testLat, float testLong)
{
    return (testLat >= topLeftLat && testLat <= bottomRightLat && testLong >= topLeftLong && testLong <= bottomRightLong);
}

Upvotes: 2

anon
anon

Reputation:

Assuming that Lat is the x coordinate und Long is the y coordinate and also assuming that the coordinate systems has its origin at the left top:

public bool IsWithinArea(float topLeftLat,float topLeftLong,
       float bottomRightLat,float bottomRightLong,float testLat,float testLong) {

          return (testLat >= topLeftLat && testLat <= bottomRightLat && testLong >= topLeftLong && testLong <= bottomRightLong);

    }

Upvotes: 1

Related Questions