androidgoogle-mapsgoogle-maps-api-3

Find Marker by Tag Google Maps API (Android)


How/Where could I get a reference of all marker objects current on the map, in order to check something like this:

if (Markers.getTag().equals("something"))

By reading the documentation on Marker it said "This is easier than storing a separate Map", so I don't want to use HashMap unless someone say I absolutely have to.

Thanks, the following is a pseudo-pseudo code

// The uid is the Marker's tag

// 1) Someway to Check if the tag exists for the current profile

// 2) If it exists, then just move the marker, just set a new position of this marker.

// 3) If it doesn't, then create a new marker, add a marker.

// 4) Set profile uid as the Marker's Tag, via .setTag()

// 5) Animate move camera to the latlng position

3-5 is okay, just 1-2

// 3) Create a new marker
                            // Marker to show on the map
                            Marker friendMarker;

                            // Add a marker when the image is loaded
                            friendMarker = googleMap.addMarker(new MarkerOptions()
                                            .position(friendLatLng)
                                            .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                                            .title(friendProfile.getName()));

                            // Set the tag on this friend marker, so we can retrieve or update it later
                            friendMarker.setTag(friendProfile.getUid());

                            // 5) Animate the camera to that location
                            CameraPosition cameraPosition = new CameraPosition.Builder().target(friendLatLng).zoom(15).build();
                            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

Solution

  • Create a List of Marker

    List<Marker> markers = new ArrayList<>();
    

    Then add your marker in your markers list

    // Marker to show on the map
    Marker friendMarker;
    
    // Add a marker when the image is loaded
    friendMarker = googleMap.addMarker(new MarkerOptions()
                   .position(friendLatLng)                     
                   .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                   .title(friendProfile.getName()));
    
    //Add now the marker in markers list
    markers.add(friendMarker);
    

    Then to access all markers

    for (Marker marker : markers) {
         if (marker.getTag().equals("something")) { //if a marker has desired tag
             //Do something in the way. Hmmmm. Yeah
         }
    }