使用Firestore中的纬度和经度向谷歌地图Flutter添加标记



对于我的Flutter应用程序,我正在尝试向谷歌地图添加标记。然而,这个标记并没有出现在地图上。我已经在Firestore中存储了纬度和经度。纬度和经度都是Firestore上的类型号。我没有把它们存储在geopoint中。

这是我的Firestore数据库的屏幕截图。

这是我从Firestore获取标记数据的代码:

String uid = FirebaseAuth.instance.currentUser.uid;
CollectionReference users = FirebaseFirestore.instance.collection('users');
getMarkerData() {
users
.doc(uid)
.collection('family')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
initMarker(doc['latitude'], doc['longitude'], doc['name']);
});
});
}

因此,这是将纬度和经度数据分配给标记的代码:

void initMarker(lat, long, name) async {
LatLng latlng = LatLng(lat, long);
var markerIdVal = name;
final MarkerId markerId = MarkerId(markerIdVal);
final Marker marker = Marker(
markerId: markerId,
position: latlng,
);
setState(() {
markers[markerId] = marker;
});
}

所以我已经解决了这个问题。

我解决问题的方法是:

  1. 我首先将位置数据存储在GeoPoint中
//Get user location and update it in Firestore
Future<void> updateUserLocation(LocationData newLocalData) {
return users
.doc(uid)
.update({
'location': GeoPoint(newLocalData.latitude, newLocalData.longitude),
})
.then((value) => print("User Updated"))
.catchError((error) => print("Failed to update user: $error"));
}
  1. 在本例中,我从Firestore中的子集合中检索了位置数据。你可以根据你的项目从任何你想要的集合中获得它
String uid = FirebaseAuth.instance.currentUser.uid;
CollectionReference users = FirebaseFirestore.instance.collection('users');
getMarkerData() {
users
.doc(uid)
.collection('family')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
initMarker(doc.data(), doc.id);
});
});
}

  1. 初始化标记
void initMarker(specify, specifyId) async {
var markerIdVal = specifyId;
final MarkerId markerId = MarkerId(markerIdVal);
final Marker marker = Marker(
markerId: markerId,
position:
LatLng(specify['location'].latitude, specify['location'].longitude),
infoWindow: InfoWindow(title: specify['name']),
);
setState(() {
markers[markerId] = marker;
//print(markerId);
});
}
  1. 在地图上显示标记
return Scaffold(
body: GoogleMap(
markers: Set<Marker>.of(markers.values),
//markers: getMarkerData(), the markers didn't show up if i use this, so i use the above instead
mapType: MapType.normal,
zoomControlsEnabled: true,
initialCameraPosition: initialLocation,
onMapCreated: (GoogleMapController controller) {
controller = controller;
},
),
);

最新更新