简体   繁体   中英

Marker on user location in Android Google Maps API v2

I mark current user location by a custom marker. I draw it once and in OnLocationChange listener I change it position according to user location, but sometimes there is a duplicate markers on the map. Why? Do you have any ideas? And is it good idea to change marker position in OnLocationChange listener?

I drawing marker:

currentUserLocationMarker = mMap.addMarker(new MarkerOptions()
                    .position(new LatLng(currentUserLocation.latitude, currentUserLocation.longitude))
                    .title("Current Location"));

and changing his position:

currentUserLocationMarker.setPosition(locLatLng);

My method looks like below. I invoke it once in onCreateView() and in OnMyLocationChangeListener() .

if (currentUserLocationMarker == null) {
            currentUserLocationMarker = mMap.addMarker(new MarkerOptions()
                    .position(new LatLng(currentUserLocation.latitude, currentUserLocation.longitude))
                    .title("Current Location"));
        } else {
            currentUserLocationMarker.setPosition(locLatLng);
        }

I suppose that better solution is draw once, and changing it position instead drawing, clearing and drawing again all the time.

Removing marker by calling method .remove() is acceptable, but clearing whole map, in the case of I have many markers and eg polylines drawn on the map is bad idea.

It would be useful if the map had a separate methods for remove markers and polylines, but now there is a one method .clear() which clear everything.

According to your description I can only say that it can only happen if currentUserLocationMarker becomes null between function call. try debugging and using logcat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM