Skip to content

Commit

Permalink
Add contains method to LngLatBounds (#8200)
Browse files Browse the repository at this point in the history
* [wip] addcontains method, but trouble with wrapped coordinates

* tests for contains point

* lint fixes

* remove comment

* Update src/geo/lng_lat_bounds.js

* minor lint / style fixes

* fix docstring
  • Loading branch information
mzdraper authored and mourner committed Nov 6, 2019
1 parent 063398e commit 94f5a36
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/geo/lng_lat_bounds.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,24 @@ class LngLatBounds {
return !(this._sw && this._ne);
}

/**
* Check if the point is within the bounding box.
*
* @param {LngLatLike} lnglat geographic point to check against.
* @returns {boolean} True if the point is within the bounding box.
*/
contains(lnglat: LngLatLike) {
const {lng, lat} = LngLat.convert(lnglat);

const containsLatitude = this._sw.lat <= lat && lat <= this._ne.lat;
let containsLongitude = this._sw.lng <= lng && lng <= this._ne.lng;
if (this._sw.lng > this._ne.lng) { // wrapped coordinates
containsLongitude = this._sw.lng >= lng && lng >= this._ne.lng;
}

return containsLatitude && containsLongitude;
}

/**
* Converts an array to a `LngLatBounds` object.
*
Expand Down
33 changes: 33 additions & 0 deletions test/unit/geo/lng_lat_bounds.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,5 +172,38 @@ test('LngLatBounds', (t) => {
t.end();
});

t.test('contains', (t) => {
t.test('point', (t) => {
t.test('point is in bounds', (t) => {
const llb = new LngLatBounds([-1, -1], [1, 1]);
const ll = {lng: 0, lat: 0};
t.ok(llb.contains(ll));
t.end();
});

t.test('point is not in bounds', (t) => {
const llb = new LngLatBounds([-1, -1], [1, 1]);
const ll = {lng: 3, lat: 3};
t.notOk(llb.contains(ll));
t.end();
});

t.test('point is in bounds that spans dateline', (t) => {
const llb = new LngLatBounds([190, -10], [170, 10]);
const ll = {lng: 180, lat: 0};
t.ok(llb.contains(ll));
t.end();
});

t.test('point is not in bounds that spans dateline', (t) => {
const llb = new LngLatBounds([190, -10], [170, 10]);
const ll = {lng: 0, lat: 0};
t.notOk(llb.contains(ll));
t.end();
});
t.end();
});
t.end();
});
t.end();
});

0 comments on commit 94f5a36

Please sign in to comment.