Reputation: 12272
I am trying to get all the markers within the bounds of the map. When the user interacts with the map (zoom in/out, move, click), I want to get all the markers within the bounds of the map to show a list of those markers.
I tried implementing some of the functions this example had without any luck: https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/
Here is a working version of the map on codepen: https://codepen.io/anon/pen/MPGgWq
I looked thru what it returned in features and bounds and none of that information helps me accomplish this. I am using the markers so I can display a custom marker image and also set the description that appears in a pop box.
map.on('moveend', function (e) {
var features = map.queryRenderedFeatures();
var bounds = map.getBounds();
console.log(features);
console.log(bounds);
});
Upvotes: 3
Views: 11827
Reputation: 29167
1) Mapbox gl js don't store references for markers
- https://github.com/mapbox/mapbox-gl-js/issues/5821#issuecomment-356704579
2) If the marker is added to the map and not saved, then its only representation is the html element inside the map container.
3) So you can use getBoundingClientRect
to determine if the marker is visible in the map container:
function intersectRect(r1, r2) {
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
}
function getVisibleMarkers() {
var cc = map.getContainer();
var els = cc.getElementsByClassName('marker');
var ccRect = cc.getBoundingClientRect();
var visibles = [];
for (var i = 0; i < els.length; i++) {
var el = els.item(i);
var elRect = el.getBoundingClientRect();
intersectRect(ccRect, elRect) && visibles.push(el);
}
if (visibles.length > 0) console.log(visibles);
}
[ https://jsfiddle.net/rkqdz5g2/ ]
Upvotes: 6
Reputation: 161
As far as I understand mapbox gl js API you cannot query markers. What I would do is have a list of markers in some kind of data structure and query using turf.js pointsWithinPolygon function. Where first input would be your markers and second your current viewport.
Upvotes: 0