How to remove map markers - java

I want to implement a map system where the user can select a point of origin and destination as two different markers.
When the user long clicks on the map they could select a button to use this location as a start or end point.
case (R.id.setStart):
markerStart = mMap.addMarker(new MarkerOptions()
.position(this.startPoint)
.title("Start")
.draggable(true)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
outputName = rGC.getStringFromCoordinates(this.startPoint.latitude, this.startPoint.longitude);
autocompleterStart.setText(outputName);
break;
case (R.id.setEnd):
markerEnd = mMap.addMarker(new MarkerOptions()
.position(this.endPoint)
.title("End")
.draggable(true)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
However, when the user repeats the same process (select a new location as start/end), I want to be able to remove the previous marker. So if they select the same START button, the previous marker for start is removed and a new one is created.
Is there a way to check if a particular marker exists on the map. I tried adding marker.remove(); but it gives me a nullpointerexception.
case (R.id.setEnd):
markerEnd.remove();
markerEnd = mMap.addMarker(new MarkerOptions()
.position(this.endPoint)
.title("End")
.draggable(true)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
Any ideas? Thanks in advanced!

you can use method which i have implemented in my app and working fine...for me
LatLng latpoint;
MAP.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
// TODO Auto-generated method stub
// MAP.clear();
if (marker != null) {
marker.remove();
}
latpoint = point;
marker = MAP.addMarker(new MarkerOptions()
.position(
new LatLng(latpoint.latitude,
latpoint.longitude))
.title(point.toString()).draggable(true)
.visible(true));
}
});

Related

Ignore marker click without hiding marker

I have a google maps fragment with a few markers that have a marker click event, in that mapFragment I also have a map click listener that calculates the distance between 2 clicks in the map, the problem is that if I click close to the marker the marker gets the event, I tried returning true, but I still cant click behind the marker. Is there any way to completely ignore the marker if I click near it?
I have simple marker click that puts the marker in front if its clicked, I return false because I want to consume the vent myself.
gMap.setOnMarkerClickListener(marker -> {
if (mSelectedMarker != null) {
mSelectedMarker.setZIndex(marker.getZIndex());
}
marker.setZIndex(Float.MAX_VALUE);
mSelectedMarker = marker;
return false;
});
The I also have a mapClickListener that can be enabled and disabled, that checks for 2 map clicks and draws 2 markers and a polyline between them.
onMapClickListenerRegla = new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(#NonNull LatLng latLng) {
// incomplete code
if (markerReglaInicio == null) {
markerReglaInicio = gMap
.addMarker(new MarkerOptions()
.position(latLng)
.anchor(0.5F, 0.5F)
.icon(bitmapDescriptorFromVector(requireContext(),
R.drawable.marker_utilidades_coordenadas)));
return;
}
Maps fragment with my custom marker and 2 circles from the map click event

How to update marker positions with data from Firebase Google Maps API Android

I'm creating an app that makes a real time tracking of users using Firebase Database. Every user is displayed in the map using markers.
When there is a new location update, the marker has to be updated. The problem is that with Firebase method onDataChange() or similars every time a new location update is retrieved, I can't access to the old marker to remove it and create a new one or just update the old marker, because the marker doesn't exist.
I tried it saving markers in SharedPreferences using Gson, but when I pass the marker to json, the app crashes.
Does anyone know how can I update the markers?
This is written inside the onDataChange():
for (User user: usersList) {
Gson gson = new Gson();
/*
String previousJson = preferences.getString(user.getId()+"-marker", "");
Marker previousMarker = gson.fromJson(previousJson, Marker.class);
if (previousMarker!=null) markerAnterior.remove();
*/
final LatLng latlng = new LatLng(user.getLastLocation().getLatitude(), user.getLastLocation().getLongitude());
MarkerOptions markerOptions = new MarkerOptions()
.position(latlng)
.title(user.getId());
Marker marker= mMap.addMarker(markerOptions);
// String newJson = gson.toJson(marker); //CRASH
// editor.putString(user.getId()+"-marker", newJson);
// editor.commit();
}
Thank you.
Create a HashMap instance variable that will map user IDs to Markers:
private Map<String, Marker> mMarkerMap = new HashMap<>();
Then, populate new Markers in the HashMap so you can retrieve them later.
If the Marker already exists, just update the location:
for (User user : usersList) {
final LatLng latlng = new LatLng(user.getLastLocation().getLatitude(), user.getLastLocation().getLongitude());
Marker previousMarker = mMarkerMap.get(user.getId());
if (previousMarker != null) {
//previous marker exists, update position:
previousMarker.setPosition(latlng);
} else {
//No previous marker, create a new one:
MarkerOptions markerOptions = new MarkerOptions()
.position(latlng)
.title(user.getId());
Marker marker = mMap.addMarker(markerOptions);
//put this new marker in the HashMap:
mMarkerMap.put(user.getId(), marker);
}
}

Android Google Maps - remove marker with icon

I want to remove a Marker on long click, and place it in another place without clearing the whole map.
Right now the circle radius works fine, but the custom pin icon is not removed.
using the GoogleMap.clear() method should not be used - there are some other objects on the map I don't want refreshed.
I have also tried setPosition method and had the very same result.
How to erase this icon?
Marker declaration:
marker = googleMap.addMarker(new MarkerOptions().position(marker.getPosition()).draggable(true).title("INFO")
.infoWindowAnchor(0.5f,0.5f).visible(false)
.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.pin_icon))));
this.googleMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
if (marker != null) {
marker.remove();
}
createMarker(latLng);
}
});
private void createMarker(LatLng latLng) {
marker = googleMap.addMarker(new MarkerOptions().position(latLng).draggable(true).title("INFO")
.infoWindowAnchor(0.5f,0.5f)
.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_pin_gr))));
}
I used such approach for creating markers and simply setPosition(new Latlng(...)) working.
marker = mGoogleMap.addMarker(new MarkerOptions()
.anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pin))
.position(new LatLng(cab.getLatitude(), cab.getLongitude())));
Did you try to replace marker.remove(); on setPosition() inside onLongClick() method ?

How do I change the colour of all markers on a map at the same time in android? How do I only change the colour of some of the markers?

Situation 1:
Say I populate a map with blue markers as such:
for (LatLng latLng : latLngList) {
mMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
}
On clicking a marker, I wish to change the colour of every marker on the map to yellow. How would I do this?
Currently, I can only manage to change the colour of the specific marker that I click on using this method:
#Override
public boolean onMarkerClick(Marker marker) {
//change marker colour to yellow
marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
return false;
}
Situation 2:
Say I have 2 kinds of markers, blue and red, created from two different lists of latLngs.
//create blue markers
for (LatLng latLng : latLngListBlue) {
mMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
}
//create red markers
for (LatLng latLng : latLngListRed) {
mMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
On clicking a red marker, I want all blue markers to change to yellow. How would I do this?
You need to keep a reference to your markers and then modify them when you want.
List<Marker> mMarkers = new Arraylist<Marker>();
for (LatLng latLng : latLngList) {
Marker marker = mMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMarkers.add(marker);
}
and then
#Override
public boolean onMarkerClick(Marker marker) {
//change marker colour to yellow
marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
for(Marker otherMarker : mMarkers) {
otherMarker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
}
return false;
}
similar workaround for the second situation
You can achieve it by saving a list for all of the markers with an id for the color. You can use List with a POJO with Marker and the Id like this:
public class MarkerWithColor {
private Marker marker;
private int colorId; // red = 0, green = 1, blue = 2
public MarkerWithColor(Marker marker, int colorId) {
this.marker = marker;
this.colorId = colorId;
}
// getter
// setter
}
Then, each time you adding the marker, create the pojo and save to the list:
List<MarkerWithColor> markerWithColors = new ArrayList<>();
// adding blue marker
for (LatLng latLng : latLngList) {
Marker marker = mMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
// add to the list
markerWithColors.add(new MarkerWithColor(marker, 2)); // 2 is blue color
}
/* Do the same for the red and green */
// Now you can change the specific color
// Change blue to yellow
for(int i = 0; i < markerWithColors.size(); i++) {
MarkerWithColor markerWithColor = markerWithColors.get(i);
markerWithColor.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
}
You can also use Enum instead of int for the colorId. And you can also use Pair instead of the POJO.

Android - Google Map make marker sticky

I have following marker code on my MapFragment. I want this marker stick to it's position. Means I want marker at center position in map and when I move/drag map then marker shouldn't get moved. How to do that with following marker?
PlaceMarker = PlaceMap.addMarker(
new MarkerOptions()
.position(new LatLng(0, 0))
.draggable(true)
.title("Drag Me"));
PlaceMarker.showInfoWindow();
Thanks
You can add a listener when the user pans the map and set the marker on the center.
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
public void onCameraChange(CameraPosition cameraPosition) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(cameraPosition.target));
}
});
Another way of doing this is by overlaying a marker icon (Not a real marker; defined in your XML layout) and get the location when the user sets that as a location.
You would want to set draggable to false
public void setDraggable (boolean draggable)
The sets the draggability of the marker.

Categories

Resources