繁体   English   中英

如何将 Firestore 中的 GeoPoint 转换为 LatLng

[英]How to convert GeoPoint in Firestore to LatLng

您好,我正在使用 Android Studio,但在转换从 Firestore 获得的数据时遇到了问题。 我将数据保存在我的 Firestore 类型 GeoPoint 中,我想查询它并将其转换为对象类型LatLng

这是我的代码:

    final FirebaseFirestore db = FirebaseFirestore.getInstance();
    final CollectionReference stores = db.collection("stores");
    stores.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.i(TAG,document.getData().get("position").toString());
                        }
                    } else {
                        Log.w(TAG, "Error getting documents.", task.getException());
                    }
                }
            });

这是我得到的

    12-16 10:59:21.557 28239-28239/com.company.yummy.yummy I/firebaseCatch: GeoPoint { latitude=29.339555, longitude=169.715858 }
    12-16 10:59:21.557 28239-28239/com.company.yummy.yummy I/firebaseCatch: GeoPoint { latitude=68.085393, longitude=-42.081575 }
    12-16 10:59:21.557 28239-28239/com.company.yummy.yummy I/firebaseCatch: GeoPoint { latitude=16.503923, longitude=90.196118 }
    12-16 10:59:21.557 28239-28239/com.company.yummy.yummy I/firebaseCatch: GeoPoint { latitude=-69.424524, longitude=-71.356333 }
    12-16 10:59:21.557 28239-28239/com.company.yummy.yummy I/firebaseCatch: GeoPoint { latitude=69.502257, longitude=71.100474 }

我需要的只是获取纬度、经度值以设置到 LatLng 对象中。

要解决这个问题,您可以简单地使用getGeoPoint()方法,如下所示:

GeoPoint geoPoint = document.getGeoPoint("position");

然后使用:

double lat = geoPoint.getLatitude();
double lng = geoPoint.getLongitude();
LatLng latLng = new LatLng(lat, lng);

这对我有用 flutter cloud_firestore

void getData() {
databaseReference
    .collection("stores")
    .getDocuments()
    .then((QuerySnapshot snapshot) {
  snapshot.documents.forEach((f) {
    print('${f.data}}');
    GeoPoint pos = f.data['position'];
    LatLng latLng = new LatLng(pos.latitude, pos.longitude);

  });
});
}

参考 - https://fireship.io/lessons/flutter-realtime-geolocation-firebase/

您需要从接收到的 Geopoint 对象中提取纬度和经度,

并创建一个新的 LatLng 对象,就像这样

double lat = document.getData().get("position").getLatitude();
double lng = document.getData().get("position").getLongitude ();
LatLng latLng = new LatLng(lat, lng);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM