Reputation: 2443
I am playing with google maps (android studio), and trying to limit the number of markers a single user can pin. I couldn't find any examples online, only thing I could find is removing the current marker (code below).
My goal is to allow the user to pin only 3 markers.
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng arg0) {
//if there is a marker already this if condition removes it
if (marker != null) {
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_02))
.position(
new LatLng(arg0.latitude,
arg0.longitude))
.draggable(true).visible(true));
}
});
Upvotes: 0
Views: 676
Reputation: 2443
Edited Shvet's code a little bit. After pinning 3 markers user is unable to pin fourth, and he gets a quick message.
int markerCount = 0; //marker counter
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng arg0) {
if (markerCount < 3) {
markerCount = markerCount+ 1;
marker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.position(new LatLng(arg0.latitude, arg0.longitude))
.draggable(true)
.visible(true));
} else {
Toast.makeText(getApplicationContext(), "Only 3 markers allowed!",
Toast.LENGTH_LONG).show();
}
}
}
Upvotes: 0
Reputation: 1043
int marker_count=0;
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng arg0) {
if(marker_count<3){
//if there is a marker already this if condition removes it
if (marker != null) {
marker.remove();
marker_count=marker_count-1;
}
marker_count=marker_count+1;
marker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_02))
.position(
new LatLng(arg0.latitude,
arg0.longitude))
.draggable(true).visible(true));
}}
else{
//toast a message
}
});
Upvotes: 3