Get all markers visible at current zoom level (unfolding)

I have a very large set of features that outline city borders. Trying to convert them all to markers and load all onto a map at once seems to be bogging down my app.

What I’d like to do instead is only show these city border markers at an appropriate zoom level, and only those that are in the current view. This is what I have tried, with some small success:

public void mapChanged(MapEvent mapEvent){
        if (mapEvent.getType().equals(PanMapEvent.TYPE_PAN) 
                || mapEvent.getType().equals(ZoomMapEvent.TYPE_ZOOM)){
            List<Marker> toAdd = new LinkedList<>();
            List<Marker> toRemove = new LinkedList<>();
            if (map.getZoomLevel() > 6){
                for (Marker m : cityBorderMarkers){
                    if (map.isHit(map.getScreenPosition(m.getLocation()))){

However, it seems that using map.isHit(ScreenPosition) returns true even for locations that are a decent ways outside the current view and sometimes returns false even if the location is clearly in the center of the map.

Any solution is appreciated.

1 Like

I’ve had a similar problem. I was looking for which points are inside a rectangle or was it squares inside a rectangle. Anyway this looks to be identical problem: map points inside a square set by the window.

Solution was to sort points first by x and second by y value. To find all points inside a rectangle, with x1,y1 and x2,y2 marking corners of the rectangle, you can use binary search (works with sorted list of coordinates) to find first point in the list that is inside the rectangle using x1,y1. And same with the last point using x2,y2. All points between them are inside the rectangle(x1,y1,x2,y2). Those points would be you map markers inside the rectangle set by the window.

Binary search is really fast. Sorting takes awhile, but you need to do it only once or after you add map markers.

Hope this helps.