我有一个应用程序,它将使用实时Firebase的最新纬度和经度更新谷歌地图标记。我在谷歌地图上删除标记时遇到了问题,问题是当地图上出现新的标记时,无法删除以前的标记。我试着使用GoogleMap.clear()
,但它似乎不起作用。有人知道是什么导致了这个问题吗?谢谢
我的代码
public class PoliceMapActivity extends FragmentActivity implements OnMapReadyCallback {
//initialize all variables
DatabaseReference reff;
GoogleMap map;
String RecordId;
Marker marker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_police_map);
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.police_map);
supportMapFragment.getMapAsync(PoliceMapActivity.this);
//get record Id
RecordId = getIntent().getStringExtra("recordId");
reff = FirebaseDatabase.getInstance().getReference().child("Records");
Thread thread = new Thread() {
@Override
public void run() {
try {
while (isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
// update onmapready()
if (supportMapFragment != null) {
supportMapFragment.getMapAsync(PoliceMapActivity.this);
if (marker != null) {
map.clear();
}
}
}
});
}
} catch (InterruptedException e) {
}
}
};
thread.start();
}
@Override
public void onMapReady(GoogleMap googleMap) {
map.clear();
final DatabaseReference finalreff = reff.child(RecordId);
finalreff.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
Double lat = (Double) snapshot.child("latitude").getValue();
Double lon = (Double) snapshot.child("longitude").getValue();
String name = snapshot.child("Fullname").getValue().toString();
LatLng latLng = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions().position(latLng).title(getIntent().getStringExtra(name)));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
您可能在另一个对象上调用了map.clear((,而不是在代码中显示的googleMap实例上。尝试在onDataChange 方法中调用googleMap.clear((