2

I need to check whether a point lies within a given rectangle on a map. I am using leaflet to create bounding boxes which requires me to provide the south-west and north-east points of the rectangle.

I have the following information: 1. middle point of the top edge of the rectangle 2. middle point of the bottom edge of the rectangle 3. length of edge (i.e. breadth) = 1000 m.

It is safe to assume that the two points above are very close.

Any ideas on how this can be achieved will be helpful.

user1628340
  • 901
  • 4
  • 14
  • 27

1 Answers1

1

First, to get the upper left and lower right points, you'll need to use some geometry. This page: https://gis.stackexchange.com/questions/2951/algorithm-for-offsetting-a-latitude-longitude-by-some-amount-of-meters is a great example of how to accurately convert from meters to decimal degrees.

For example, in order to get the upper-left point, you are starting with the middle point of the line, and you have the total length of the line, you'll want to divide the length of the line by 2, then convert that length from meters to decimel degrees, then add the X coordinate by that amount. That will give you the upper-right corner. Repeat this for the lower-left corner by subtracting that amount instead of substracting.

var upperMiddlePoint = [30,50];
var segmentLength = 5000;
var northEastPoint = upperMiddlePoint;
var northEastPoint.x = northEastPoint.x + ((segmentLength / 2) * DECIMAL_DEGREES_PER_METER)

There's a quick and easy answer here: Simple calculations for working with lat/lon + km distance? that describes how to get the DECIMAL_DEGREES_PER_METER value in the above snippet.

To create a LatLngBounds object to represent your rectangle bounds. API Here.

var bounds = new L.LatLngBounds(southWestPoint, northEastPoint);

Then, use the LatLngBounds.contains() function, as described here, to determine if your point falls within these bounds.

var contains = bounds.contains([50, 30]);
if (contains) {
     doStuff();
}

The contains boolean will be true if the bounds contain the point, false if not.

Community
  • 1
  • 1
Patrick D
  • 6,659
  • 3
  • 43
  • 55
  • I am aware of the above function. What my question how to calculate the southWestPoint and northEastPoint, when I have the data mentioned in the question – user1628340 Sep 05 '13 at 12:26
  • Seems like a simple problem of geometry then. Can you subtract 1/2 of the length of your edge (say 500m) from the middle point top edge X coordinate, in order to get the upper left corner? Then do the same for the bottom? – Patrick D Sep 05 '13 at 13:34
  • Added some code to the beginning of my answer to describe this. – Patrick D Sep 05 '13 at 13:52