我正在尝试使用当前位置打开谷歌地图。为此,我使用了一个有状态的小部件。但是地图需要很长时间才能加载,有时甚至根本无法加载。这是因为Future
函数(用于获取当前位置)还是我的实现错误?我正在为地图使用google_maps_flutter插件。这是我的代码:
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
FutureBuilder(
future: _getCurrentLocation(),
builder: (context, snapshot) {
if (snapshot.hasData) {
print("map loaded");
Placemark placemark = snapshot.data;
var json = placemark.toJson();
selectedLocation = TheLocation.fromJson(json);
_markers.add(
Marker(
markerId: MarkerId('homeMarker'),
position: LatLng(
selectedLocation.latitude, selectedLocation.longitude),
icon: BitmapDescriptor.defaultMarker,
infoWindow: InfoWindow(title: selectedLocation.name),
draggable: false,
),
);
return GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(placemark.position.latitude,
placemark.position.longitude),
zoom: 18,
),
markers: _markers,
onMapCreated: onMapCreated,
onCameraMove: ((_position) => _updatePosition(_position)),
);
} else {
print("loading map");
return Container(
child: Center(
child: Text("Loading map. Please Wait ... ..."),
),
);
}
},
),
],
),
);
}
使用地理定位器插件获取当前位置:
Future<Placemark> _getCurrentLocation() async {
List<Placemark> placeMarks;
await geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) async {
placeMarks = await Geolocator().placemarkFromCoordinates(
position.latitude,
position.longitude,
localeIdentifier: "en_US",
);
}).catchError((e) {
print("Location error $e");
});
return placeMarks[0];
}
onMapCreated
功能 :
void onMapCreated(GoogleMapController controller) {
setState(() {
googleMapController = controller;
});
}