integrating the user location doesn't work - google-maps

I tried to build an application, which shows the current user location. In order to achieve this goale, I used Google-Map and location plug-in. I tried a sample I found in the internet, but I get an error and don't know why... I think I did it the same like the guy in the video did it...
This is the ode I tried:
void _onMapCreated(GoogleMapController controller) {
_controller = controller;
_location.onLocationChanged().listen((l) {
_controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(l.latitude, l.lomgitude), zoom: 10)));
});
}
child: GoogleMap(
markers: markers,
initialCameraPosition: position,
mapType: MapType.hybrid,
onMapCreated: _onMapCreated,
myLocationButtonEnabled: true,
),
This is the error I get:
Compiler message:
lib/main.dart:42:32: Error: 'onLocationChanged' isn't a function or method and can't be invoked.
_location.onLocationChanged().listen((l) {
^^^^^^^^^^^^^^^^...
Does anybody find my mistake?

You can remove () of onLocationChanged()
please change from
_location.onLocationChanged().listen((l) {
_controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(l.latitude, l.lomgitude), zoom: 10)));
});
to
_location.onLocationChanged.listen((l) {
_controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(l.latitude, l.lomgitude), zoom: 10)));
});

Related

How to turn off the 'find me' FAB in Flutter Google maps plugin?

I am having zero luck turning off the floating action button which exists on the Google maps view in Flutter. I have tried restarting the app, hotreload, delete/reinstall, no luck.
Here's my code:
return Card(
child: GoogleMap(
compassEnabled: false,
mapToolbarEnabled: false,[![enter image description here][1]][1]
padding: EdgeInsets.all(1),
mapType: MapType.normal,
myLocationButtonEnabled: false,
myLocationEnabled: false,
initialCameraPosition: _curCamera,
markers: Set<Marker>.of(_markers),
polylines: Set<Polyline>.of(_polylines),
onMapCreated: (GoogleMapController controller) async {
staticMapController = controller;
positionList = await tracksDB.getListOfPositions(widget.trackID);
setState(() {
_polylines.add(Polyline(
polylineId: PolylineId('track1'),
visible: true,
points: positionList,
color: Colors.red,
));
});
},
),
);
Latest package version fixed the problem. google_maps_flutter: ^1.0.3

How can I execute bloc event continuously in Flutter?

I want to follow user location continuously in my application. For this reason, I want to execute getLocaiton bloc event continuously in my main page. How can I do that?
Here is the my getLocation event;
GetLocationState get initialState => GetLocationState(saveUserCurrentLocation: initialPosition );
Stream<GetLocationState> mapEventToState(LocationEvent event) async*{
if (event is GetLocation){
userLocation.getLocation().then((l){
currentLatLng = LatLng(l.latitude, l.longitude);
});
yield GetLocationState(saveUserCurrentLocation: currentLatLng);
}
}
And this my my main page
initialCameraPosition:
CameraPosition(target: initialPosition, zoom: 10),
mapType: MapType.terrain,
onMapCreated: _onMapCreated,
myLocationEnabled: true,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_locationBloc.add(GetLocation());
},
),
),
);
});
}
How can I run code continuously in the background, without using onPress event?
use a Timer inside initState() (make you widget stateful if it isn't):
Timer(Duration(seconds: 5), (){
_locationBloc.add(GetLocation());
});

Flutter: How to place the mylocation button on Google Maps at different positions?

I'm using Google Maps and by default the myLocation button shows up on the topRight corner. I want it at the bottom right corner.
I can't seem to have any property inside GoogleMap widget
GoogleMap(
myLocationEnabled: true,
myLocationButtonEnabled: true,
initialCameraPosition: CameraPosition(
target: _currentLocation,
zoom: 11.0,
),
onMapCreated: _onMapCreated,
),
Try using FloationgButton
GoogleMap(
mapType: MapType.hybrid,
initialCameraPosition: _kGooglePlex,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
myLocationEnabled: true,
),
floatingActionButton: FloatingActionButton.extended(
onPressed: _currentLocation,
label: Text('My Location'),
icon: Icon(Icons.location_on),
),
);
}
also set with the current location
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: 17.0,
),
));
}

How does drop pins with long press on google map with flutter?

I'm new to flutter.
I'm trying to drop pins on map with flutter,
Here I got the current location with geolocator package and set a marker
GoogleMap(
onMapCreated: (controller){
mapController=controller ;
},
mapType: _currentMapType,
myLocationEnabled: true,
initialCameraPosition: CameraPosition(
target:_center,
zoom: 11.0,
),
markers: {
//Marker for current Location
Marker(
markerId: MarkerId("marker"),
position: LatLng(currentPosition.latitude, currentPosition.longitude),
infoWindow: InfoWindow(title: 'Current Location'),
icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed)
)
},
),
I was recently working on this code, it may help you.
1.- First define the markers in this way (do it as a global variable):
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
2.- Create the Google Maps widget:
#override
Widget build(BuildContext context) {
return new Scaffold(
body: Stack(
children: [Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: GoogleMap(
mapType: _defaultMapType,
myLocationEnabled: true,
myLocationButtonEnabled: true,
initialCameraPosition: _currentposition,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
compassEnabled: true,
tiltGesturesEnabled: false,
onLongPress: (latlang) {
_addMarkerLongPressed(latlang); //we will call this function when pressed on the map
},
markers: Set<Marker>.of(markers.values), //all markers are here
)
)]
),
);
}
3.- Create the function (method) '_addMarkerLongPressed':
Future _addMarkerLongPressed(LatLng latlang) async {
setState(() {
final MarkerId markerId = MarkerId("RANDOM_ID");
Marker marker = Marker(
markerId: markerId,
draggable: true,
position: latlang, //With this parameter you automatically obtain latitude and longitude
infoWindow: InfoWindow(
title: "Marker here",
snippet: 'This looks good',
),
icon: BitmapDescriptor.defaultMarker,
);
markers[markerId] = marker;
});
//This is optional, it will zoom when the marker has been created
GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newLatLngZoom(latlang, 17.0));
}
I hope I've helped :)

Flutter - Google Maps doesn´t wait to Location

I´m trying to show a map with current location. For do this i used Location and Google Map plugins (last version).
I have a code similar to:
var lng, lat;
#override
initState() {
super.initState();
loading = true;
getLocation();
}
Future getLocation() async {
final location = Location();
var currentLocation = await location.getLocation();
setState(() {
lat = currentLocation.latitude;
lng = currentLocation.longitude;
loading=false;
});
}
loading==false ? GoogleMap(
mapType: MapType.hybrid,
myLocationButtonEnabled: true,
myLocationEnabled: true,
initialCameraPosition: CameraPosition(
target: LatLng(lat, lng),
zoom: 15.0,
)):null,
When we go the view with map a error appear around 1s (then view load properly) with this error in the console
I/flutter (15567): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY
╞═══════════════════════════════════════════════════════════ I/flutter
(15567): The following assertion was thrown building
HomePageScreen(dirty, dependencies: I/flutter (15567):
[_LocalizationsScope-[GlobalKey#78c30], MediaQuery], state:
_HomePageScreen#9c9d2): I/flutter (15567): 'package:google_maps_flutter/src/location.dart': Failed assertion:
line 17 pos 16: 'latitude != I/flutter (15567): null': is not true.
I debug it and the error is relative simple: The Location plugin load latitude and longitude slow , Google Maps plugin load more fast. So we have a error.
The question is: How can i force Google map to wait location and longitude from Location plugin?
Show an empty Container() or any loading indicator while your lat and lng is null.
lat == null || lng == null
? Container()
: GoogleMap(
mapType: MapType.hybrid,
myLocationButtonEnabled: true,
myLocationEnabled: true,
initialCameraPosition: CameraPosition(
target: LatLng(lat, lng),
zoom: 15.0,
),
);
you can display a loader until you get your location,
var lng, lat;
#override
initState() {
super.initState();
loading = true;
getLocation();
}
Future getLocation() async {
final location = Location();
var currentLocation = await location.getLocation();
setState(() {
lat = currentLocation.latitude;
lng = currentLocation.longitude;
loading=false;
});
}
loading==false ? GoogleMap(
mapType: MapType.hybrid,
myLocationButtonEnabled: true,
myLocationEnabled: true,
initialCameraPosition: CameraPosition(
target: LatLng(lat, lng),
zoom: 15.0,
)):CircularProgressIndicator(),
You can also try this, and get rid of the empty Container.
GoogleMap(
mapType: MapType.hybrid,
myLocationButtonEnabled: true,
myLocationEnabled: true,
initialCameraPosition: CameraPosition(
target: LatLng(lat ?? 0, lng ?? 0), // so if lat, lng is null, we use 0 as placeholder.
zoom: 15.0,
),
)