Reputation: 55
In my app i need to have 2 types of markers: the first ones need to stay on a location and the second ones need to move, right now I dont have the static markers yet but my app can show a marker moving if the location of the phone changes but for that i call mMap.clear(), I dont want to clear all markers when the location changes so I need to remove only that marker, I read in another question that I need to use Marker.remove(); to remove individual markers but im not sure where to implement that in the code.
Here is the method for a new location:
public void onLocationChanged(Location location) {
mMap.clear();
GetLatLong();
handleNewLocation(location);
mCurrentLocation = location;
}
and here is the handleNewLocation method:
private void handleNewLocation(Location location) {
if (mLastLocation != null) {
LatLng latLng = new LatLng(list.get(0), list.get(1));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//añadir un nuevo marker con la posición de la variable latLng
MarkerOptions camion = new MarkerOptions()
.position(latLng)
.title("Camión")
.snippet("ruta " + ruta)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.bus));
Marker marker = mMap.addMarker(camion);
if (marker == null) {
mMap.addMarker(camion);
} else {
camion.position(latLng);
}
}
}
Thank you.
EDIT:
List<Marker> markers = new ArrayList<Marker>();
@Override
public void onLocationChanged(Location location) {
markers.clear();
GetLatLong();
handleNewLocation(location);
mCurrentLocation = location;
}
private void handleNewLocation(Location location) {
if (mLastLocation != null) {
LatLng latLng = new LatLng(list.get(0), list.get(1));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//añadir un nuevo marker con la posición de la variable latLng
MarkerOptions camion = new MarkerOptions()
.position(latLng)
.title("Camión")
.snippet("ruta " + ruta)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.bus));
Marker marker = mMap.addMarker(camion);
if (marker == null) {
markers.add(marker);
} else {
camion.position(latLng);
}
}
}
}
Upvotes: 1
Views: 3220
Reputation: 20944
If you want to remove one marker - you have to remember this marker first. Then call marker.remove().
Code:
class YourClass {
Marker singleMarker; //marker to be removed
public void addMarker() {
....
//here you add your marker
singleMarker = mMap.addMarker(camion);
}
public void removeSingleMarker() {
if(singleMarker != null) {
singleMarker.remove();
singleMarker = null;
}
}
}
Upvotes: 7
Reputation: 6078
As I discussed above, you can try to save the what-you-want-remove marker
in an ArrayList
or in a HashMap
.
Sample code:
// before loop:
List<Marker> markers = new ArrayList<Marker>();
// inside your loop:
Marker marker = myMap.addMarker(new MarkerOptions().position(new LatLng(geo1Dub,geo2Dub))); //...
markers.add(marker);
// after loop:
markers.size();
Upvotes: 1