Search code examples
androidmapsmapboxmapbox-markermapbox-android

Hide and show markers on MapBox


When I started this, I thought this is a rather trivial feature, but I keep struggling to achieve this:

On a MapBox map on Android, I want to hide all markers when I zoom out (at a certain zoom level), and show them again when I zoom in.

I couldn't find any option to hide (set visibility to false) the markers. So I remove them and add them again:

private void hideMarkers() {
    if (!markersHidden) {
        mapBoxMap.clear();
        markersHidden = true;
    }
}

private void showMarkers() {
    if (markersHidden) {
        markersHidden = false;
        for (Point point : markerMap.values()) {
            addMapMarker(point);
        }
    }
}

public void addMapMarker(Point point) {
    if (point == null) return;

    markerMap.put(point.id, point);
    if (markersHidden) return;

    MarkerOptions markerOptions = new MarkerOptions()
            .position(new LatLng(point.location.latitude, point.location.longitude))
            .setSnippet(point.id)
            .icon(IconUtils.drawableToIcon(getContext(), presenter.getMapIcon(point.provider).getMapIcon(point)))
            .title(point.name);

    mapBoxMap.addMarker(markerOptions);
}

Where markerMap is a HashMap where I keep my Point references. The methods do what they are supposed to do. markerMap keeps the references, and they are properly added to the map. However, they are not shown.

Why are they not showing up on the map when they are added to it?
What can I do to show the markers again?
Is there any other way in which I can achieve hiding and showing the markers apart from removing and adding them?

The MapBox version I'm using is com.mapbox.mapboxsdk:mapbox-android-sdk:5.0.2@aar.


Solution

  • I think it is possible to manage to hide and show the markers only if you use MarkerView. As a prof of concept here is a code showing how it works through the method setVisibility

    markerView = map.addMarker(new MarkerViewOptions()
                        .anchor(.5f, .5f)
                        .icon(IconFactory.getInstance(getApplicationContext()).fromResource(R.drawable.mapbox_marker_icon_default))
                        .position(stuttgartLoc));
    
                CameraUpdate cameraNewPosition = CameraUpdateFactory
                        .newLatLngZoom(stuttgartLoc, 17);
                map.animateCamera(cameraNewPosition);
    
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        markerView.setVisible(false);
                    }
                }, 5000);
    
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        markerView.setVisible(true);
                    }
                }, 10000);