I want something like the following:
const bounds = map.getBounds()
const itemPos = new MapboxGl.LngLat(coordinates.longitude, coordinates.latitude)
bounds.contains(itemPos)
but apparently according to LngLatBounds
documentation https://www.mapbox.com/mapbox-gl-js/api/#LngLatBounds LngLatBounds.contains
is not a method there. So is there anything else that I can use to determine if a LngLat
is a part of the LngLatBounds
or do I need to implement it myself ?
Mapbox is a map rendering library, and lack a lot of common geospatial methods. If you want to do geospatial calculations and don't want to re-invent the wheel, I'd recommend turf.js.
Totally with @kristfal on this one. If you don't care about unwrapped coordinates, you can hack it with LngLatBounds.extend()
. Just call it and check if the bounds changed by extending them 馃槈
@vypah thanks for your feature request. We do recommend using turf.js for spatial analysis queries like the one you've requested. For this use case, I think turf#inside will work for you.
Thanks for the responses. I still think these kind of handy methods should be a part of mapboxgl itself like the way leaflet provides all these methods. For now I wrote the method myself but having this inside mapboxgl will be really amazing 馃憤
you can extend this method to map instance.
public inBounds(lnglat: [number, number]) {
const bounds = this.getBounds();
const lng = (lnglat[0] - bounds['_ne']['lng']) * (lnglat[0] - bounds['_sw']['lng']) < 0;
const lat = (lnglat[1] - bounds['_ne']['lat']) * (lnglat[1] - bounds['_sw']['lat']) < 0;
return lng && lat;
}
[this] is the map instance.
I should notice that the inBounds
method above is incorrect. It will fail as soon as you have 180 degree line of longitude inside your bounds.
You can avoid it with the function below:
const inBounds = function (bounds, lnglat) {
let lng;
const multLng = (lnglat[0] - bounds['_ne']['lng']) * (lnglat[0] - bounds['_sw']['lng']);
if (bounds['_ne']['lng'] > bounds['_sw']['lng']) {
lng = multLng < 0;
} else {
lng = multLng > 0;
}
const lat = (lnglat[1] - bounds['_ne']['lat']) * (lnglat[1] - bounds['_sw']['lat']) < 0;
return lng && lat;
};
Most helpful comment
Thanks for the responses. I still think these kind of handy methods should be a part of mapboxgl itself like the way leaflet provides all these methods. For now I wrote the method myself but having this inside mapboxgl will be really amazing 馃憤