我正在尝试在谷歌地图上添加一些来自 firebase 的标记,但无法弄清楚为什么这些标记不出现在谷歌地图上(在 UI 上)。有人可以帮助我或建议我更新教程吗?
void main() => runApp(Parkings());
class Parkings extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: '...',
home: MapSample(),
debugShowCheckedModeBanner: false,
);
}
}
class MapSample extends StatefulWidget {
@override
State<MapSample> createState() => MapSampleState();
}
class MapSampleState extends State<MapSample> {
final FirebaseFirestore _database = FirebaseFirestore.instance;
Completer<GoogleMapController> _controller = Completer();
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
void _changeMap(LatLng position) async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(
bearing: 0,
target: LatLng(position.latitude, position.longitude),
zoom: 20.0,
),
));
}
@override
void initState() {
addParkings();
super.initState();
}
这就是我尝试获取数据和创建标记的方式:
addParkings() {
_database
.collection('places')
.where('name', isEqualTo: "School")
.where('name', isEqualTo: "Theatre")
// ignore: deprecated_member_use
.getDocuments()
.then((docs) {
// ignore: deprecated_member_use
if (docs.documents.isNotEmpty) {
// ignore: deprecated_member_use
for (int i = 0; i < docs.documents.length; i++) {
// ignore: deprecated_member_use
initMarker(docs.documents[i].data, docs.documents[i].documentID);
}
}
});
}
void initMarker(parking, parkingid) {
var markerIdVal = parkingid;
final MarkerId markerId = MarkerId(markerIdVal);
// creating a new MARKER
final Marker marker = Marker(
markerId: markerId,
position: LatLng(parking['Latitud'], parking['Longitud']),
infoWindow: InfoWindow(title: parking['name']),
);
setState(() {
// adding a new marker to map
markers[markerId] = marker;
});
}
static final CameraPosition _kGooglePlex = CameraPosition(
target: LatLng(45.7936, 24.1213),
zoom: 12.4746,
);
在这里,我在地图上添加标记:
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('Parking Wizard'),
backgroundColor: Colors.deepPurpleAccent,
),
body: GoogleMap(
mapType: MapType.hybrid,
initialCameraPosition: _kGooglePlex,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
myLocationEnabled: true,
markers: Set<Marker>.of(markers.values)),
floatingActionButton: FloatingActionButton(
onPressed: _currentLocation,
),
);
}
我使用这个函数来获取设备的当前位置:
void _currentLocation() async {
final GoogleMapController controller = await _controller.future;
LocationData currentLocation;
var location = new Location();
try {
currentLocation = await location.getLocation();
} on Exception {
currentLocation = null;
}
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(
bearing: 0,
target: LatLng(currentLocation.latitude, currentLocation.longitude),
zoom: 18.0,
),
));
}
}