2
votes

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.

1

1 Answers

1
votes

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.