'Flutter - Load Google Map Markers from Firestore
I am developing a Flutter app and one of the functions is a map with locations. I made a database with the locations in Firestore but I am unable to load the markers.
I don't get any errors and it looks like the app is connecting fine but it does not display the markers...
Can someone please help me with this?
Below my code, thank you!
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:hvd_test/styling/colors.dart';
class StationsMap extends StatefulWidget {
@override
_StationsMap createState() => _StationsMap();
}
class _StationsMap extends State<StationsMap> {
bool mapToggle = false;
var currentLocation;
GoogleMapController mapController;
Map<MarkerId , Marker> markers = <MarkerId , Marker>{};
getMarkerData() async {
FirebaseFirestore.instance.collection('hvd-stations').get().then((myMarkers) {
if(myMarkers.docs.isNotEmpty) {
for(int i = 0; i < myMarkers.docs.length ; i++){
initMarker(myMarkers.docs[i].data , myMarkers.docs[i].id);
}
}
});
}
void initMarker(specify , specifyId) async {
var markerIdVal = specifyId;
final MarkerId markerId = MarkerId(markerIdVal);
final Marker marker = Marker(
markerId: markerId,
position: LatLng(specify['stationLocation'].latitude , specify['stationLocation'].longitude),
infoWindow: InfoWindow(title: 'HvD Stations' , snippet: specify['stationAddress']),
);
setState(() {
markers[markerId] = marker;
});
}
void initState() {
getMarkerData();
super.initState();
Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high).then((currloc) {
setState(() {
currentLocation = currloc;
mapToggle = true;
});
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Stack(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height - 80.0,
width: double.infinity,
child: mapToggle ?
GoogleMap(
onMapCreated: onMapCreated,
myLocationEnabled: true,
initialCameraPosition: CameraPosition(target: LatLng(currentLocation.latitude, currentLocation.longitude),
zoom: 10.0,
),
markers: Set<Marker>.of(markers.values),
):
Center(child:
CircularProgressIndicator(),
)
)
],
),
),
);
}
void onMapCreated(controller) {
setState(() {
mapController = controller;
});
}
}
Solution 1:[1]
When I did the implementation of Firestore I made a mistake with the placement of the document you add to your project. After reading the documentation I ran the implementation again with no issues and it is now working fine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | EnricovanDijkhuizen |