Android markerOption未与google地图中的当前标记一起移动

Android markerOption未与google地图中的当前标记一起移动,android,google-maps,google-maps-api-3,Android,Google Maps,Google Maps Api 3,我尝试制作一个可以与谷歌地图一起使用的应用程序。在我的地图中,我有currentmarker和markeroption,当我移动当前标记(蓝点)时,它会移动,但markeroption(红旗,带有CurrenrtLocation标记)没有与当前标记(蓝点)一起移动。我如何在谷歌地图中制作可以与当前标记一起移动的markeroption。谢谢 将currentLocationMarker设为类属性,实际上,在添加它之后,您正在删除它 class YourActivity extends Acti

我尝试制作一个可以与谷歌地图一起使用的应用程序。在我的地图中,我有currentmarker和markeroption,当我移动当前标记(蓝点)时,它会移动,但markeroption(红旗,带有CurrenrtLocation标记)没有与当前标记(蓝点)一起移动。我如何在谷歌地图中制作可以与当前标记一起移动的markeroption。谢谢


将currentLocationMarker设为类属性,实际上,在添加它之后,您正在删除它

class YourActivity extends Activity implements onMapReady {

    private Marker currentLocationMarker;

    @Override
    public void onLocationChanged(Location location){

        if ( location != null ){
            if ( currentLocationMarker == null ){
                currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
            }else{
                currentLocationMarker.setPosition(new LatLng(location.getLatitude(), location.getLongitude()));
            }
        }

    }

}
解释

在您的代码中,您可以在位置第一次更改时添加一个标记,然后在每次位置更改时添加一个新标记,并使用以下命令立即将其删除:

Marker currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
//...
if (!firstPass){
    currentLocationMarker.remove();
}

最好的做法是保留对您创建的标记的引用,而不是将其删除创建一个新的标记,只需更新其位置,即我在代码中所做的操作,如果标记不存在(currentLocationMarker==null),则创建它并在类中保留引用。如果存在标记(else),则只需更新其位置。

您能解释更多吗?
Marker currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
//...
if (!firstPass){
    currentLocationMarker.remove();
}