Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
});