使用GeoFlutterFire从Firebase Firestore读取地理点遇问题求助
Firestore地理点数据读取问题求助
我已成功将数据推送至Firebase Firestore,但在尝试读取地理点数据时遇到问题,恳请帮助,谢谢。
我的尝试代码
void getDrivers(){ geoFlutterFire = Geoflutterfire(); GeoFirePoint geoFirePoint = GeoFirePoint(latitude, longitude); var ref = _firebaseFirestore.collection('Drivers'); var locations = geoFlutterFire.collection(collectionRef: ref) .within(center: geoFirePoint, radius: maxRadius, field: 'position'); locations.listen((List<DocumentSnapshot> documentList) { for (var documentSnapshot in documentList) { Map<String,Object> documentShot = documentSnapshot.get('geopoint'); dynamic lat = documentShot['Latitude']; dynamic lon = documentShot['Longitude']; markers.add(Marker( markerId: MarkerId(DateTime.now().millisecond.toString()), position: LatLng(lat,lon), icon: BitmapDescriptor.defaultMarker )); Fluttertoast.showToast(msg: 'markers Size ' + markers.length.toString()); } }); }
Firestore数据结构

错误信息

错误指向代码中的documentSnapshot.get('geopoint');这一行。
问题原因及解决方法
从数据截图能看到,Firestore里的geopoint字段是Firebase原生的GeoPoint类型,不是你代码里假设的普通Map结构,直接强转类型会导致类型不匹配错误。
修改代码中读取地理点的部分:
// 替换原代码中Map<String,Object>相关的三行 GeoPoint geoPoint = documentSnapshot.get('geopoint') as GeoPoint; double lat = geoPoint.latitude; double lon = geoPoint.longitude;
另外注意:你调用geoFlutterFire.within时指定的查询字段是'position',但Firestore里实际存储地理点的字段是'geopoint',两者必须保持一致,否则无法正确查询到目标数据,请检查字段名是否匹配。
内容的提问来源于stack exchange,提问作者Taki
相关产品推荐
相关产品推荐

