所以我的FireBase数据库中有多个位置: Database Structure
写下这个循环遍历所有这些节点,提取经度和纬度,然后将它们显示为标记。
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("locations");
final GeoFire geoFire = new GeoFire(ref);
//Add a location
//geoFire.setLocation("meetFar2", new GeoLocation(26.173027, -80.252871));
final GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(userLocation.latitude, userLocation.longitude), 5.7);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
@Override
public void onKeyEntered(String key, GeoLocation location) {
System.out.println(String.format("Key %s entered the search area at [%f,%f]", key, location.latitude, location.longitude));
Query locationQuery = FirebaseDatabase.getInstance().getReference().child("locations");
locationQuery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()){
Double latitude = (Double) snap.child("l/0").getValue();
Double longitude = (Double) snap.child("l/1").getValue();
LatLng meetLatLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(meetLatLng));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onKeyExited(String key) {
System.out.println(String.format("Key %s is no longer in the search area", key));
}
@Override
public void onKeyMoved(String key, GeoLocation location) {
System.out.println(String.format("Key %s moved within the search area to [%f,%f]", key, location.latitude, location.longitude));
}
@Override
public void onGeoQueryReady() {
}
@Override
public void onGeoQueryError(DatabaseError error) {
Toast.makeText(MainActivity.this, "There was an error with this query " + error, Toast.LENGTH_SHORT).show();
}
});
在我获得用户的最后一个已知位置(设置为userLocation)之后,这一切都在onMapReady中完成。但是,当我运行程序时,如果查询的半径中至少有一个键,则地图会显示所有标记。如何仅将半径内的查询结果显示为标记?
答案 0 :(得分:0)
意识到初始queryAtLocation查询从我的数据库返回正确数量的点,所以我删除了其中的第二个查询。代码现在看起来像这样:
final GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(userLocation.latitude, userLocation.longitude), 7.0);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
@Override
public void onKeyEntered(String key, GeoLocation location) {
System.out.println(String.format("Key %s entered the search area at [%f,%f]", key, location.latitude, location.longitude));
LatLng meetLatLng = new LatLng(location.latitude, location.longitude);
googleMap.addMarker(new MarkerOptions().position(meetLatLng));
}