当我的位置发生变化时,它会添加另一个标记,但不会删除前一个标记

When my location changes it adds another marker but doesn't remove the previous one

我正在使用下面的代码检查设备的当前位置。每当它更改或刷新位置时,它都会添加一个标记而不删除最后一个标记。我怎样才能删除以前的标记。

 if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                double latitude = location.getLatitude();
                double longtitude = location.getLongitude();
                LatLng latLng = new LatLng(latitude, longtitude);
                mMap.addMarker(new MarkerOptions().position(latLng).title("You Are Here"));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {
            }

            @Override
            public void onProviderEnabled(String s) {
            }

            @Override
            public void onProviderDisabled(String s) {
            }
        });
    }

或者有其他获取当前位置的方法吗?谢谢

保存addMarker方法返回的maker对象,然后可以使用marker.setPosition设置marker的新位置

实际发生的是,每当调用 locationchanged 时,都会放置新标记,但实际上在放置此标记之前,您应该清除地图。
您应该使用此 mMap.clear();,如下所示代码。
public void onLocationChanged(Location location) { mMap.clear(); double latitude = location.getLatitude(); double longtitude = location.getLongitude(); LatLng latLng = new LatLng(latitude, longtitude); mMap.addMarker(new MarkerOptions().position(latLng).title("You Are Here")); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f)); }
这样,地图将被清除,其他标记也将被删除。
通过应用程序回答,抱歉格式化,稍后编辑。

试试这个

将标记对象声明为本地

 private Marker currentMarker;

进行如下操作:

if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
        if(currentMarker!=null){
        currentMarker.remove();
        }
        double latitude = location.getLatitude();
        double longtitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longtitude);
        currentMarker=mMap.addMarker(new MarkerOptions().position(latLng).title("You Are Here"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
        }

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
        }

@Override
public void onProviderEnabled(String s) {
        }

@Override
public void onProviderDisabled(String s) {
        }
        });
        }