Search code examples
javaandroidlocationgoogle-maps-markers

How can I remove the current marker if another place is selected?


I have a autocomplete search fragment and a marker is added when there is a selected place, now what I want to do is to make the first marker to be remove if another place is selected. Tried doing some if statements but the first marker still exist, I might be doing something wrong. Any comments or suggestion would be greatly appreciated!!

Autocomplete fragment with marker

 autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
            @Override
            public void onPlaceSelected(@NonNull Place place) {
                // TODO: Get info about the selected place.
                Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());

                // Get the LatLng of the selected place
                LatLng selectedPlaceLatLng = place.getLatLng();

                // Define a new CameraPosition with desired zoom level
                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(selectedPlaceLatLng) // Sets the center of the map to the selected place's LatLng
                        .zoom(20) // Desired zoom level
                        .build();

                // Move the camera to the new position
                mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                markerSelectedLoc = mMap.addMarker(new MarkerOptions()
                        .position(selectedPlaceLatLng)
                        .flat(true));
                markerSelectedLoc.setTag(0);

            }


Solution

  • It seems that I should remove the marker first then add again the marker if its removed, here is what I did.

     // Remove the previous marker if it exists
                    if (markerSelectedLoc != null) {
                        markerSelectedLoc.remove();
                    }
    
                    // Create a new marker for the selected location
                    markerSelectedLoc = mMap.addMarker(new MarkerOptions()
                            .position(selectedPlaceLatLng)
                            .flat(true));
                }