Google Maps
google_maps_flutter: ^2.0.1 location: ^4.2.0 geocode: 1.0.1 static final LatLng _kMapCenter = LatLng(17.387140, 78.491684); LocationData? currentLocation; String address = ""; GoogleMapController? _controller; GoogleMap( initialCameraPosition: CameraPosition( target: currentLocation != null ? LatLng( currentLocation?.latitude ?? 0.0, currentLocation?.longitude ?? 0.0):_kMapCenter , zoom: 20.0, ), myLocationEnabled: true, zoomControlsEnabled: false, zoomGesturesEnabled: true, myLocationButtonEnabled: false, onMapCreated: (GoogleMapController controller) { _controller = controller; }, ),
inside onclick
_getLocation().then((value) { LocationData? location = value; _getAddress(location?.latitude, location?.longitude) .then((value) { setState(() { currentLocation = location; address = value; }); }); });
methods
Future<LocationData?> _getLocation() async { Location location = Location(); LocationData _locationData; bool _serviceEnabled; PermissionStatus _permissionGranted; _serviceEnabled = await location.serviceEnabled(); if (!_serviceEnabled) { _serviceEnabled = await location.requestService(); if (!_serviceEnabled) { return null; } } _permissionGranted = await location.hasPermission(); if (_permissionGranted == PermissionStatus.denied) { _permissionGranted = await location.requestPermission(); if (_permissionGranted != PermissionStatus.granted) { return null; } } _locationData = await location.getLocation(); _controller?.animateCamera( CameraUpdate.newCameraPosition( CameraPosition( target: LatLng(_locationData.latitude ?? 0.0, _locationData.longitude ?? 0.0), zoom: 20.0, ), ), ); return _locationData; } Future<String> _getAddress(double? lat, double? lang) async { if (lat == null || lang == null) return ""; GeoCode geoCode = GeoCode(); Address address = await geoCode.reverseGeocoding(latitude: lat, longitude: lang); return "${address.streetAddress}, ${address.city}, ${address.countryName}, ${address.postal}"; }
call inside dispose
if(_controller != null) { _controller?.dispose(); }