android – Remove previous Marker and add new Marker in Google Map v2-ThrowExceptions

Exception or error:

I want to remove a current marker after long click on map anywhere and recreate a new marker at that point. I have cleared google map on long click on map and new marker is created but the previous marker also displayed.

My Code is:

public class EditLocation extends Fragment {

View v;
Context c;
GoogleMap MAP;
Button back;
int loc;
String lat;
boolean isTapped = true;

public EditLocation(Context c, int location, String latitude) {
    // TODO Auto-generated constructor stub
    this.c = c;
    this.loc = location;
    this.lat = latitude;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    v = inflater.inflate(R.layout.map, container, false);

    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(c);
    if (status != ConnectionResult.SUCCESS) {
        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,
                (Activity) c, requestCode);
        dialog.show();
    } else {
        FragmentManager myFM = ((FragmentActivity) c)
                .getSupportFragmentManager();
        final SupportMapFragment myMAPF = (SupportMapFragment) myFM
                .findFragmentById(R.id.fragmentmap);

        MAP = myMAPF.getMap();

        MAP.setMyLocationEnabled(true);

        LocationManager locationManager = (LocationManager) c
                .getSystemService(Context.LOCATION_SERVICE);

        Criteria criteria = new Criteria();

        String provider = locationManager.getBestProvider(criteria, true);

        final Location location = locationManager
                .getLastKnownLocation(provider);
        final LatLng currentPosition = new LatLng(location.getLatitude(),
                location.getLongitude());

        MAP.setOnMapClickListener(new OnMapClickListener() {
            @Override
            public void onMapClick(LatLng point) {
                // TODO Auto-generated method stub

                MAP.addMarker(new MarkerOptions()
                        .position(currentPosition)
                        .snippet(
                                "Lat:" + location.getLatitude() + "Lng:"
                                        + location.getLongitude())
                        .icon(BitmapDescriptorFactory
                                .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                        .title("ME"));
                Log.e("lat", "" + point);

            }
        });

        MAP.setOnMapLongClickListener(new OnMapLongClickListener() {

            @Override
            public void onMapLongClick(LatLng point) {
                // TODO Auto-generated method stub

                // isTapped = false;
                MAP.clear();

                MAP.addMarker(new MarkerOptions().position(point)

                .title(point.toString()));

            }

        });

    }

    return v;

}
How to solve:

Just creat a new marker object and before adding a new marker, remove the previous one

Marker marker;

MAP.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

                @Override
                public void onMapLongClick(LatLng arg0) {
                    if (marker != null) {
                        marker.remove();
                    }
                    marker = MAP.addMarker(new MarkerOptions()
                            .position(
                                    new LatLng(arg0.latitude,
                                            arg0.longitude))
                            .draggable(true).visible(true));
                }
            });

EDIT

Do the same for OnMapClick

MAP.setOnMapClickListener(new OnMapClickListener() {
        @Override
        public void onMapClick(LatLng point) {
            // TODO Auto-generated method stub

                if (marker != null) {
                    marker.remove();
                }
            marker = MAP.addMarker(new MarkerOptions()
                    .position(currentPosition)
                    .snippet(
                            "Lat:" + location.getLatitude() + "Lng:"
                                    + location.getLongitude())
                    .icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                    .title("ME"));
            Log.e("lat", "" + point);

        }
    });

###

Just clear the google map before adding marker. Like this:

@Override
public void onMapLongClick(LatLng latLng) {
    googleMap.clear();

    googleMap.addMarker(new MarkerOptions()
            .position(latLng)
            .title(latLng.toString())
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}

###

Here a simple way You just have to change the position of the marker. Create Global Object as Marker marker;
After that add marker to map like

marker = map.addMarker(markerOptions).position(new Latlng(31.647316, 74.763791));  

And after it use marker.setPosition(newlaLng); where you need to add marker.

###

At first clear the Google map, then add a new marker.
Check the code below

mMap.clear();

//google map marker adding code here

###

Please try the blow code :-

// Global Variable...
private Marker mPreviousMarker ;

     @Override
        public boolean onMarkerClick(Marker marker) {
            if (mPreviousMarker != null) {
                mPreviousMarker.remove();

            }
            mPreviousMarker = googleMap.addMarker(new MarkerOptions().position(latLng).icon(bitmapDescriptor));
        }

LatLng :- Your latlong where you want to add and bitmapDescroptor is icon. {Just for understanding}

###

Just reposting the answer of Anthony.

The method signature for addMarker is:

public final Marker addMarker (MarkerOptions options)
So when you add a marker to a GoogleMap by specifying the options for the marker, you should save the Marker object that is returned (instead of the MarkerOptions object that you used to create it). This object allows you to change the marker state later on. When you are finished with the marker, you can call Marker.remove() to remove it from the map.

As an aside, if you only want to hide it temporarily, you can toggle the visibility of the marker by calling Marker.setVisible(boolean).

You can find the answer here Remove a marker from a GoogleMap

###

For the people who have tried the first solution in this question and you get the error of Marker has not been intialized.

Because, we are comparing the marker and null. When we have not even intialized the marker in the first place.

Solution:

Int mMarkerCount = 0; //Global Variable
Marker mMarker; //Global Variable

if(mMarkerCount > 0){
    if(mMarker != null){
        mMarker.remove();              
    }
}

mMarker = mMap.addMarker(new MarkerOptions().position(latLng));
mMarkerCount++;

The Solution for the question:

Int mMarkerCount = 0; //Global Variable
Marker mMarker;

mMap.setOnMapClickListener(new OnMapClickListener() {
    @Override
    public void onMapClick(LatLng latlng) {
        if(mMarkerCount > 0){
            if(mMarker != null){
                mMarker.remove();              
            }
        }

        mMarker = mMap.addMarker(new MarkerOptions().position(latLng));
        mMarkerCount++;  
    }
});

In the beginning, the count is going to be zero. So, the marker remove method will not be called. Once, the marker is intialized and the count is incremented. We can remove the previous marker by the help of the remove method and create a new marker as shown in the code.

Leave a Reply

Your email address will not be published. Required fields are marked *