我有一个自动完成搜索片段,并且在选择位置时添加一个标记,现在我想做的是,如果选择另一个位置,则删除第一个标记。尝试做一些 if 语句,但第一个标记仍然存在,我可能做错了什么。任何意见或建议将不胜感激!!
带标记的自动完成片段
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(@NonNull Place place) {
// TODO: Get info about the selected place.
Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
// Get the LatLng of the selected place
LatLng selectedPlaceLatLng = place.getLatLng();
// Define a new CameraPosition with desired zoom level
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(selectedPlaceLatLng) // Sets the center of the map to the selected place's LatLng
.zoom(20) // Desired zoom level
.build();
// Move the camera to the new position
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
markerSelectedLoc = mMap.addMarker(new MarkerOptions()
.position(selectedPlaceLatLng)
.flat(true));
markerSelectedLoc.setTag(0);
}
看来我应该先删除标记,然后再添加标记(如果删除了),这就是我所做的。
// Remove the previous marker if it exists
if (markerSelectedLoc != null) {
markerSelectedLoc.remove();
}
// Create a new marker for the selected location
markerSelectedLoc = mMap.addMarker(new MarkerOptions()
.position(selectedPlaceLatLng)
.flat(true));
}