I am new to flutter and trying to create a geolocation. however, for my following code, the screen only shows 'Loading.. Please wait..' and the map is not showing.
i am just trying to show the current location using dependencies
geolocator: ^6.1.1
Using the codes from
https://codelabs.developers.google.com/codelabs/google-maps-in-flutter#3
the Google map can be shown successfully. So it is not issues related to Google Maps Platform.
// home.dart
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool mapToggle = false;
var currentLocation;
GoogleMapController mapController;
@override
void initState() {
// TODO: implement initState
super.initState();
Geolocator.getCurrentPosition().then((currloc) {
setState(() {
currentLocation = currloc;
mapToggle = true;
});
});
}
void _onMapCreated(controller) {
setState(() {
mapController = controller;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Column(children: <Widget>[
Stack(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height - 80.0,
width: double.infinity,
child: mapToggle
? GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: LatLng(currentLocation.latitude,
currentLocation.longitude),
zoom: 10.0))
: Center(
child: Text(
'Loading.. Please wait..',
style: TextStyle(fontSize: 20.0),
)))
],
)
]),
);
}
}
In your AndroidManifest add permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
initialize variable
Position _currentPosition;
Copy this function and call this in initState
_getCurrentLocation() async{
Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
}).catchError((e) {
print(e);
});
}
For more info checkout their pub.dev site geolocatorunder usage,make sure you setup correctly for android and ios