20

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;

}
Nick Cox
  • 35,529
  • 6
  • 31
  • 47
Shani Goriwal
  • 2,111
  • 1
  • 18
  • 30

9 Answers9

39

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);

        }
    });
AnujMathur_07
  • 2,586
  • 2
  • 18
  • 25
  • The new Marker is creating after long click but the previous marker not remove after tap on map again though i have remove that. – Shani Goriwal Jun 29 '13 at 11:52
  • Yes...It is working nicely but the small problem is after long click the new marker created but after touch on map anywhere automatically new marker removed and previous marker displayed at the current location. – Shani Goriwal Jun 29 '13 at 12:06
  • You have added both `onClick` and `onLongClick` on map. and in both you have added the marker. So whenever you click or long click on the map, a new marker will be placed removing the previous one – AnujMathur_07 Jun 29 '13 at 12:10
  • I think you should remove the `onClick` and use only `onLongClick` on map. – AnujMathur_07 Jun 29 '13 at 12:11
  • Yes..it is but it is not possible to set clickable false after new marker created on map?? – Shani Goriwal Jun 29 '13 at 12:12
  • If you set clickable to false, then long click would also get disabled. – AnujMathur_07 Jun 29 '13 at 12:14
  • Yes...you are right..... I have also using boolean flag but it is not working...... – Shani Goriwal Jun 29 '13 at 12:15
  • Ok... i have disable onMapClick method and right now it is working properly and nice.... So thanks a lot.... – Shani Goriwal Jun 29 '13 at 12:18
5

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)));
}
Noman
  • 4,049
  • 10
  • 38
  • 59
3

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.

Inzimam Tariq IT
  • 6,548
  • 8
  • 42
  • 69
  • Yeah, it works. I tried this and then posted it here. – Inzimam Tariq IT Jan 31 '20 at 14:34
  • 1
    this works, but you may want to hide the marker after initialization, until you actually need it. You can set [visibility in MarkerOptions](https://developers.google.com/android/reference/com/google/android/gms/maps/model/MarkerOptions#visible(boolean)) – lasec0203 Apr 09 '20 at 03:23
3

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

mMap.clear();

//google map marker adding code here
Md. Rejaul Karim
  • 694
  • 7
  • 14
1

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}

sharma_kunal
  • 2,152
  • 1
  • 28
  • 28
0

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

Community
  • 1
  • 1
Sagar Devanga
  • 2,815
  • 27
  • 30
0

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.

Ashfaq nisar
  • 2,500
  • 1
  • 12
  • 22
0

googleMap.clear();

@Override
public void onMapReady(GoogleMap googleMap) {

    MarkerOptions markerOptions = new MarkerOptions();
    LatLng latLng = new LatLng(address.getLat(), address.getLng());
    markerOptions.position(latLng);
    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));
    googleMap.addMarker(markerOptions);

    googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {
            if (touchMarker != null) {
                touchMarker.remove();
            }
            googleMap.clear();
            MarkerOptions markerOptions = new MarkerOptions().position(latLng);
            touchMarker = googleMap.addMarker(markerOptions);
            address.setLat(touchMarker.getPosition().latitude);
            address.setLng(touchMarker.getPosition().longitude);
           
        }
    });
}
Community
  • 1
  • 1
Meysam Keshvari
  • 1,141
  • 12
  • 14
0

Simple Solution: Add this line of code before adding some markers in google map

Marker mMarker; //Global Variable

if (marker != null) 
    marker.remove();

mMarker = mMap.addMarker(new MarkerOptions().position(latLng));
Hamza Khalid
  • 191
  • 1
  • 7