使用Google Map

时间:2017-01-12 16:57:26

标签: android google-maps firebase firebase-realtime-database

我的Capstone项目需要帮助。我知道从Google Firebase检索数据的一些基础知识,但我遇到了问题。我的Firebase结构如下所示:

BusNumber {
  9009 {
      Location: "10.134342,  124.8380294"
  }
  9010 {
      Location: "10.248606, 124.750047"
  } 
  9011 {
      Location: "10.035522, 124.982952"
  }
}

我想检索所有坐标并在Google地图上绘制所有坐标。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

假设" BusNumber"是你的RootNode(否则你必须在调用addChildEventListener之前调整初始引用)..

@Override
public void onMapReady(GoogleMap googleMap) {
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
    reference.addChildEventListener(new ChildEventListener(){
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
            String title = dataSnapshot.getKey();
            LatLng position = getLatLngFromString(dataSnapshot.child("Location").getValue(String.class));
            googleMap.addMarker(new MarkerOptions()
                    .position(position)
                    .title(title));
        }
        /* Other Overriden Methods Omitted */
    });
}


public static LatLng getLatLngFromString(String s) {
    String[] a = s.split("\\s*,\\s*");
    if (a.length > 2 || a[0].isEmpty() || a[1].isEmpty()) {
        throw new IllegalArgumentException("LatLng String is not valid!");
    }
    return new LatLng(Double.parseDouble(a[0]), Double.parseDouble(a[1]));
}

这应该让你开始。显然你需要注册/取消注册childeventlistener,处理ChildEventListener中的其他方法等。

我假设您已经设置了GoogleMap,如果还没有,请参阅官方指南:https://developers.google.com/maps/documentation/android-api/map-with-marker

答案 1 :(得分:0)

您应该尝试使用https://github.com/firebase/geofire-java来处理GeoLocation数据。我认为这是按位置查询数据的最简单方法等。

基本上,您将获得Firebase查询的结果,并使用以下代码:

geoFire.getLocation("firebase-hq", new LocationCallback() {
    @Override
    public void onLocationResult(String key, GeoLocation location) {
        if (location != null) {
            System.out.println(String.format("The location for key %s is [%f,%f]", key, location.latitude, location.longitude));
        } else {
            System.out.println(String.format("There is no location for key %s in GeoFire", key));
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        System.err.println("There was an error getting the GeoFire location: " + databaseError);
    }
});

希望它能帮到你!