Google Maps API v2
Whilst I was waiting for another app to be finalised I was creating another out of interest that would only enable 1 marker to be added to a map at a time (I love maps I do).

I currently have this code which will clear the map if a marker already exists and then add another one. But what I wanted was for it to show a message telling to user to clear the map before it will allow another marker to be added.

@Override
    public void onMapClick(LatLng position){
        if (position != null){
            mMap.clear();
            mMap.addMarker(new MarkerOptions()
            .position(position)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher_new)));
        }
        else {
            mMap.addMarker(new MarkerOptions()
            .position(position)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher_new)));           
        }
    }

I tried:

@Override
    public void onMapClick(LatLng position){
        if (position != null){
            Toast.makeText(this, "Clear map before adding another location", Toast.LENGTH_SHORT).show();

        }
        else {
            mMap.addMarker(new MarkerOptions()
            .position(position)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher_new)));           
        }
    }

But all that does is show the message I want even when no markers exist so you can't actually add any markers. Should I be utilizing ArrayList here? The app will only allow 1 marker at a time by design. I have looked around and not found anything specific to my needs before asking.

Thanks

This is my edited code, which still doesn't work:

@Override
    public void onMapLongClick(LatLng position) {
        mMap.clear();
        Toast.makeText(this, "Position Cleared", Toast.LENGTH_SHORT).show();
        position = null;
    }

    @Override
    public void onMapClick(LatLng position){
        if (position != null){
            Toast.makeText(this, "Clear first", Toast.LENGTH_SHORT).show();
            /*mMap.clear();
            mMap.addMarker(new MarkerOptions()
            .position(position)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher_new)));*/
        }
        else {
            mMap.addMarker(new MarkerOptions()
            .position(position)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher_new)));           
        }
    }

It is still not letting me add a marker after I have cleared the map using onMapLongClickListener

有帮助吗?

解决方案

addMarker returns a Marker object you can use to update or indicate that you created the Marker already.

You can also use the Marker object to remove it from the map instead of clear() that removes all markers.

in pseudo code:

Marker marker;

if(marker == null) {
   marker = map.addMarker(...)
} else {
   ....
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top