Search code examples
androiditemizedoverlay

Remove itemizedOverlay during onLocationChanged


What I want to achieve is to have 2 kinds of markers displayed on a map.

1)Red markers that display events drawn from a database (done that - itemizedOverlay)

2)Orange marker which will dynamically display the user's location on the map(itemizedOverlay2).

I'm using ItemizedOverlay to have the 2 different layers (one for events and one for user location) but I have an issue with the dynamic marker that shows user position.

ISSUE:

What happens is the LocationListener successfully gets the latitude/longitude and places a point on the map BUT the previous point still exists. So I have a trail of markers showing the user's location.

I have implemented a few ways I found searching the internet but none of which happen during the calling of onLocationChanged.

class myLocationListener implements LocationListener{
        OverlayItem overlayItem;


        @Override
        public void onLocationChanged(Location location) {

            if (location != null){

                mapOverlays.remove(itemizedOverlay2);
                mapView.invalidate();

                lat = location.getLatitude();
                longi = location.getLongitude();
                GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (longi * 1E6));
                mControl.animateTo(point);

                overlayItem = new OverlayItem(point, "My Location", "This is probably where you are");
                itemizedOverlay2.addOverlay(overlayItem);
                mapOverlays.add(itemizedOverlay2);

            }

        }

I know that you might need more of my code but let's just stay at this block see if someone sees where I'm getting it wrong.

Thank you.


Solution

  • You haven't posted the code for the class that itemizedOverlay2 belongs to, but I'm guessing it extends ItemizedOverlay. Since it has an addOverlay() method, I'm also guessing that it has a .clear() method.

    If so, the you should call the clear() before you add the new location

    itemizedOverlay2.clear();
    itemizedOverlay2.addOverlay(overlayItem);