我希望此问题能解决,请帮助我解决此问题。 我正在使用Resburrpi-3,将位置数据的经度和纬度上传到Firebase上,现在我想在latlong参考上的Google地图上使用Firebase来检索经度和纬度。
private DatabaseReference mReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = mReference.child("Tezgam");
usersRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for (DataSnapshot snapm: dataSnapshot.getChildren()) {
latitude = snapm.child("lat").getValue(Long.class);
longitude = snapm.child("long").getValue(Long.class);
Speed = snapm.child("speed").getValue(String.class);
}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("Tezgam\n Current location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}`
答案 0 :(得分:0)
在onMapReady()
方法中可用数据之前,您的onDataChanged()
方法可能已被触发。我假设您遇到的错误是“纬度”和“经度”为空(假设,因为操作没有显示如何声明变量)。这是一个竞争条件-一种方法在另一种方法可以提供数据之前完成。您必须容纳丢失的数据。
因此,像这样更改您的onMapReady()
代码:
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
updateMapLocation();
}
并将您的快照代码更改为:
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for (DataSnapshot snapm: dataSnapshot.getChildren()) {
latitude = snapm.child("lat").getValue(Long.class);
longitude = snapm.child("long").getValue(Long.class);
Speed = snapm.child("speed").getValue(String.class);
updateMapLocation();
}
}
现在,添加updateMapLocation()
方法,该方法将检查纬度和经度值是否为空,否则显示位置:
private void updateMapLocation(){
if(latitude == null || longitude == null){
Log.e("updateMapLocation", "latitude or longitude is null")
}
else{
LatLng sydney = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("Tezgam\n Current location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}