Answer First
SO what I here do, first I get current location using the geolocator: ^6.1.13
plugin and simply save it into one variable and until get current location show empty container and then pass the current location to the target
value in Google map
class SelectionScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return _selectionScreen();
}
}
class _selectionScreen extends State<SelectionScreen> {
@override
initState() {
loading = false;
getCurrentLocation();
super.initState();
}
bool loading;
var start_currentPostion;
getCurrentLocation() async {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
setState(() {
double latitude = position.latitude;
double longitude = position.longitude;
start_currentPostion = LatLng(latitude, longitude);
loading = true;
});
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: loading ? GoogleMap(
mapType: MapType.normal,
initialCameraPosition: CameraPosition(
target: start_currentPostion,
zoom: 14,
),
onMapCreated: (GoogleMapController controller) {},
myLocationEnabled: true,
) : Container());
}
}
Answer Second
So in your GoogleMapPage
You just need to add one boolean value and update this on the basis of location
bool getLocationLoading;
Add this value in your initState()
and set it as false after that again call this boolean variable to your getLocation()
method and set it as true
@override
void initState() {
super.initState();
getLocation();
getLocationLoading = false; // set false
}
getLocation() async {
var location = new Location();
location.onLocationChanged.listen((currentLocation) {
print(currentLocation.latitude);
print(currentLocation.longitude);
setState(() {
latLng = LatLng(currentLocation.latitude, currentLocation.longitude);
});
print("getLocation:$latLng");
_onAddMarkerButtonPressed();
getLocationLoading = true; // set true
});
}
and then simply add your GoogleMap
to your body part
body: getLocationLoading ? GoogleMap(
polylines: _polyLines,
markers: _markers,
mapType: MapType.normal,
initialCameraPosition: CameraPosition(
target: latLng,
zoom: 14,
),
onCameraMove: onCameraMove,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
myLocationEnabled: true,
), : Container());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…