Google Maps camera position updating issues in Flutter - google-maps

I'm building an application with Flutter, based on a map. So I use the Google Maps package and all's working fine. But, I tried to add a FloatingActionButton to recenter the map on my location, and here, I got a problem. First, the map doesn't recenter on my location and second, I get an horrible red error. Here are the code, the flutter doctor, and the error code.
My code:
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:provider/provider.dart';
import 'package:spotycar/providers/location_service.dart';
import '../../models/user_location.dart';
class MapWidget extends StatefulWidget {
MapWidget({#required Key key}) : super(key: key);
#override
_MapWidgetState createState() => _MapWidgetState();
}
var locationClicked = false;
class _MapWidgetState extends State<MapWidget> {
#override
Widget build(BuildContext context) {
CameraUpdate cameraUpdate;
GoogleMapController mapController;
var location = Provider.of<UserLocation>(context);
final provider = Provider.of<LocationService>(context);
final double _zoom = 17.0;
final double _tilt = 37.0;
var _coord;
if (provider.loadedLocation) {
_coord = LatLng(location.latitude, location.longitude);
cameraUpdate = CameraUpdate.newCameraPosition(CameraPosition(
target: _coord,
bearing: location.heading,
zoom: _zoom,
tilt: _tilt,
));
}
if (locationClicked == true) {
mapController.moveCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: _coord,
bearing: location.heading,
zoom: _zoom,
tilt: _tilt,
),
),
);
setState(() {
locationClicked = false;
});
}
return Scaffold(
body: !provider.loadedLocation
? Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.purple),
),
)
: GoogleMap(
onMapCreated: (GoogleMapController controller) {
mapController = controller;
mapController.animateCamera(cameraUpdate);
},
myLocationEnabled: true,
myLocationButtonEnabled: false,
zoomControlsEnabled: false,
initialCameraPosition: CameraPosition(
target: _coord,
zoom: _zoom,
tilt: _tilt,
),
rotateGesturesEnabled: true,
),
);
}
}
class LocationRechercheWidget extends StatefulWidget {
#override
_LocationRechercheWidgetState createState() =>
_LocationRechercheWidgetState();
}
class _LocationRechercheWidgetState extends State<LocationRechercheWidget> {
#override
Widget build(BuildContext context) {
return FloatingActionButton(
child: Icon(
Icons.location_searching,
color: Colors.purple,
size: 25,
),
backgroundColor: Colors.white,
onPressed: () {
setState(() {
locationClicked = true;
});
},
);
}
}
My Flutter doctor :
[√] Flutter (Channel master, 1.20.0-3.0.pre.124, on Microsoft Windows [version 10.0.18362.900], locale fr-FR)
• Flutter version 1.20.0-3.0.pre.124 at C:\flutter
• Framework revision ec3368ae45 (2 days ago), 2020-07-02 01:58:01 -0400
• Engine revision 65ac8be350
• Dart version 2.9.0 (build 2.9.0-20.0.dev f8ff12008e)
[√] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
• Android SDK at C:\Users\adrie\AppData\Local\Android\sdk
• Platform android-29, build-tools 29.0.2
• Java binary at: C:\Program Files\Android\Android Studio1310\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
• All Android licenses accepted.
[√] Android Studio (version 3.6)
• Android Studio at C:\Program Files\Android\Android Studio1310
• Flutter plugin version 45.1.1
• Dart plugin version 192.7761
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
[√] VS Code (version 1.46.1)
• VS Code at C:\Users\adrie\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.12.1
[√] Connected device (1 available)
• Mi Note 10 (mobile) • 53bd04cc • android-arm64 • Android 10 (API 29)
• No issues found!
And The error that I'm getting when I click on the FloatingActionButton :
═╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building MapWidget-[#2721f](dirty, dependencies:
[InheritedProvider<UserLocation>, InheritedProvider<LocationService>], state:
_MapWidgetState#50617):
The method 'moveCamera' was called on null.
Receiver: null
Tried calling: moveCamera(Instance of 'CameraUpdate')
The relevant error-causing widget was:
MapWidget-[#2721f]
lib\screen\map_screen.dart:20
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _MapWidgetState.build
package:spotycar/…/map_screen/map_widget.dart:39
#2 StatefulElement.build
package:flutter/…/widgets/framework.dart:4663
#3 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4546
#4 StatefulElement.performRebuild
package:flutter/…/widgets/framework.dart:4719
#5 Element.rebuild
package:flutter/…/widgets/framework.dart:4262
#6 BuildOwner.buildScope
package:flutter/…/widgets/framework.dart:2667
#7 WidgetsBinding.drawFrame
package:flutter/…/widgets/binding.dart:866
#8 RendererBinding._handlePersistentFrameCallback
package:flutter/…/rendering/binding.dart:286
#9 SchedulerBinding._invokeFrameCallback
package:flutter/…/scheduler/binding.dart:1115
#10 SchedulerBinding.handleDrawFrame
package:flutter/…/scheduler/binding.dart:1054
#11 SchedulerBinding._handleDrawFrame
package:flutter/…/scheduler/binding.dart:970
#15 _invoke (dart:ui/hooks.dart:253:10)
#16 _drawFrame (dart:ui/hooks.dart:211:3)
(elided 3 frames from dart:async)

To solve this issue, you need to use a Completer instead of a simple GoogleMapController.
When you instantiate it :
Completer<GoogleMapController> _controller = Completer();
Then in the onMapCreated method inside your GoogleMap widget :
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
...
},
And whenever you wanna change the camera position :
Future<void> moveCamera() async {
final GoogleMapController controller = await _controller.future;
controller.moveCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: LatLong(..., ...),
zoom: ...,
)));
}
And you should be good !

I had this issue, I had the exact code that was being used by Vayhuit. My pin would update but the cam whent to the last place I had searched. to solve this I had to change
static final CameraPosition _location = CameraPosition(
target: LatLng(lat!, lng!),
zoom: 15,
);
I had an init state so I created a
late CameraPosition _location;
and then
getLocation() {
_location = CameraPosition(
target: LatLng(lat!, lng!),
zoom: 15,
);
}
Then I just added getLocation(); to the initstate. seems to work now.

For those who are using FlutterMap or MapBox in Flutter
The above answers are right but I will add one thing, that was a big problem for me as well. How to keep the zoom level according to the user zoom because when you listen for the current location changes and update your camera position according to it then the zoom level is also picking the one that you provide at the start.
for example: you provide the zoom level 13 at the start and you zoom the screen to 16 then when the camera position updates it will bring you again to zoom level 13, and it is repeating after every second which is really annoying, So you have to provide the zoom level dynamically which will change according to the user zoom level.
First Listen to the location stream:
location.onLocationChanged.listen((event) {
final newLatLng = LatLng(event.latitude!, event.longitude!);
// Use mapController to access the move method
// move() method is used for the camera position changing e.g: move(LatLng center, double zoom)
mapController.move(newLatLng , 13); // this will set the zoom level static to 13
// but we want it to be dynamic according to the user zoom level,
// so then use the mapController.zoom property will dynamically adjust your zoom level
mapController.move(newLatLng , mapController.zoom);
});

Related

How do I remove a Null exception on a themed map and is it worth it?

I have a map app that uses google_map_flutter package and displays a full screen themed map. My confusion is that when I build the app I receive an unhandled exception for setMapStyle, even though the map displays with the theme.
Unhandled Exception: NoSuchMethodError: The method 'setMapStyle' was
called on null. E/flutter (30877): Receiver: null E/flutter (30877):
Tried calling: setMapStyle("[\r\n {\r\n \"featureType\":
\"landscape\",\r\n \"elementType\": \"geometry\",\r\n.......
The theme is a json file that I load using the code in my initState below.
#override
void initState() {
super.initState();
// Show the campus Map
getSunData();
// _showCampusMap();
WidgetsBinding.instance.addObserver(this);
// Check location permission has been granted
PermissionHandler()
.checkPermissionStatus(PermissionGroup
.locationWhenInUse) //check permission returns a Future
.then(_updateStatus); // handling in callback to prevent blocking UI
rootBundle
.loadString('assets/themes/map/day/simple_bright.json')
.then((string) {
mapStyle = string;
});
getUserLocation();
}
My method for setting the style is here.
// method that is called on map creation and takes a MapController as a parameter
void _onMapCreated(GoogleMapController controller) async {
PermissionHandler()
.checkPermissionStatus(PermissionGroup
.locationWhenInUse) //check permission returns a Future
.then(_updateStatus); // handling in callback to prevent blocking UI
controller.setMapStyle(mapStyle);
}
Here is my GoogleMap code
_userLocation == null
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(
backgroundColor: Theme.UniColour.primary[900],
),
SizedBox(height: 20.0),
Text("Retrieving your location..."),
],
),
)
: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: // required parameter that sets the starting camera position. Camera position describes which part of the world you want the map to point at.
CameraPosition(
target: _userLocation,
zoom: _defaultZoom,
tilt: _tiltAngle), //LatLng(53.467125, -2.233966)
scrollGesturesEnabled: _scrollGesturesEnabled,
tiltGesturesEnabled: _tiltGesturesEnabled,
compassEnabled: _compassEnabled,
rotateGesturesEnabled: _rotateGesturesEnabled,
myLocationEnabled: _myLocationEnabled,
buildingsEnabled: _buildingsEnabled, // not added to db
indoorViewEnabled: _indoorViewEnabled, // not added to db
mapToolbarEnabled: _mapToolbarEnabled, // not added to db
myLocationButtonEnabled:
_myLocationButtonEnabled, // not added to db
mapType: _currentMapType,
zoomGesturesEnabled: _zoomGesturesEnabled,
cameraTargetBounds: CameraTargetBounds(
new LatLngBounds(
northeast: uniCampusNE,
southwest: uniCampusSW,
),
),
minMaxZoomPreference:
MinMaxZoomPreference(_minZoom, _maxZoom),
),
Any ideas why this exception is occurring, does it need fixing and how would I do that?
[EDIT]
void _updateStatus(PermissionStatus status) {
if (status != _status) {
// check status has changed
setState(() {
_status = status; // update
_onMapCreated(controller);
});
} else {
if (status != PermissionStatus.granted) {
//print("REQUESTING PERMISSION");
PermissionHandler().requestPermissions(
[PermissionGroup.locationWhenInUse]).then(_onStatusRequested);
}
}
}
The argument type 'Completer' can't be assigned
to the parameter type 'GoogleMapController'.
[/EDIT]
thanks
You need to initialize the Completer class, under your State class write the following:
Completer<GoogleMapController> _controller = Completer();
Then use the variable _controller when calling setMapStyle:
void _onMapCreated(GoogleMapController controller) async {
PermissionHandler()
.checkPermissionStatus(PermissionGroup
.locationWhenInUse) //check permission returns a Future
.then(_updateStatus); // handling in callback to prevent blocking UI
_controller.setMapStyle(mapStyle);
}

Including markers in google map for flutter based on Json file

I'm trying to add marker to my map widget based on the string in a Json file. However i have no idea how the marker thingy works after the .addMarker no longer applied. Can anyone please explain on it?
The markers: attribute in the Flutter_Google_maps widget now takes a Set<Marker>().
to add markers, first you should create an empty Set of type Marker and assign it to the markers: attribute in the google maps widget. Consequently, you append the desired Marker() to the created set using the add() method. Finally, you use setState() to rebuild the widget and display the updated Markers set on the UI.
Example:
class MapsScreen extends StatefulWidget {
#override
_MapsScreenState createState() => _MapsScreenState();
}
class _MapsScreenState extends State<MapsScreen> {
Completer<GoogleMapController> _mapsController = Completer();
Set<Marker> _myMarkers = Set<Marker>();
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
_myMakers.add(
markerId: MarkerId("current"),
position: LatLng(yourLatitude, yourLongitude),
);
setState((){});
)},
),
body: GoogleMap(
initialCameraPosition: _anyCameraPosition,
markers: _myMarkers,
onMapCreated: (GoogleMapController controller) {
_mapsController.complete(controller);
},
);
);
}
}
you have the option to use any state management pattern you prefer.

How to mock 'google_maps_flutter' package for flutter tests?

I've recently started getting into flutter, but just as I was about to write a few widget tests, I noticed that I wasn't terribly sure how to mock out the Google Maps Flutter package.
Many examples I've seen include using the library "mockito" to mock out classes, but this assumes that the Google Maps widget will be injected into the widget to be tested. Unfortunately, with their given documentation and startup guide, this doesn't seem to be very possible:
class MapsDemo extends StatefulWidget {
#override
State createState() => MapsDemoState();
}
class MapsDemoState extends State<MapsDemo> {
GoogleMapController mapController;
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Center(
child: SizedBox(
width: 300.0,
height: 200.0,
child: GoogleMap(
onMapCreated: _onMapCreated,
),
),
),
RaisedButton(
child: const Text('Go to London'),
onPressed: mapController == null ? null : () {
mapController.animateCamera(CameraUpdate.newCameraPosition(
const CameraPosition(
bearing: 270.0,
target: LatLng(51.5160895, -0.1294527),
tilt: 30.0,
zoom: 17.0,
),
));
},
),
],
),
);
}
void _onMapCreated(GoogleMapController controller) {
setState(() { mapController = controller; });
}
}
Note that the GoogleMaps widget cannot be passed in because onMapCreated is a required function, and that function relies private class method (give the parent widget access to GoogleMapsController). Many other examples of mockito mock functions that don't have this sort of callback function to set state.
There doesn't seem to be any other packages I've seen that can effectively mock out the GoogleMaps widget, so I don't really have any sort of example to follow. Ideally, what I was expecting was some sort of behavior like proxyquire or sinon in node.s (where you don't need to pass in the mocked libraries into function.constructors), but it looks like mockified classes need to be passed into the tested widgets.
Are there any other ideas on how to mock out this library for testing? Or should I just live with testing the actual functionality?
I managed to mock the GoogleMaps by mocking the channels it uses:
setUpAll(() async {
SystemChannels.platform_views.setMockMethodCallHandler((MethodCall call) {
switch (call.method) {
case 'create':
return Future<int>.sync(() => 1);
default:
return Future<void>.sync(() {});
}
});
MethodChannel('plugins.flutter.io/google_maps_0', StandardMethodCodec())
.setMockMethodCallHandler((MethodCall methodCall) async {
return null;
});
}
I got inspiration from this webview plugin test (which is a PlatformView like the GoogleMaps widget), as well as this GoogleMaps plugin test

Get Visible Markers in google_maps_flutter

Using Google Maps for Flutter I've placed some markers on different places on the map. I have a separate RaisedButton on my Flutter app which I need to only be visible when one or more of those markers are currently visible on the map.
How can this be achieved? I've found a somewhat similar solution for Google Maps API but I need this for google_maps_flutter on Flutter.
LatLngBounds has specific method known as contains() which works along with GoogleMapController's getVisibleRegion().
From the official docs:
contains(LatLng point) → bool
Returns whether this rectangle contains the given LatLng.
Usage:
Completer<GoogleMapController> _controller = Completer();
static final CameraPosition _positionCenter = CameraPosition(
target: LatLng(40.730610, -73.935242),
zoom: 3.5,
);
Future<LatLngBounds> _getVisibleRegion() async {
final GoogleMapController controller = await _controller.future;
final LatLngBounds bounds = await controller.getVisibleRegion();
return bounds;
}
#override
Widget build(BuildContext context) {
void checkMarkers() async {
LatLngBounds bounds = await _getVisibleRegion();
Set<Marker> markers = Set<Marker>.of(markers.values);
markers.forEach((marker) {
print('Position: ${ marker.position } - Contains: ${ bounds.contains(marker.position) }');
});
}
return GoogleMap(
mapType: MapType.normal,
markers: Set<Marker>.of(markers.values),
initialCameraPosition: _positionCenter,
onCameraIdle: () {
checkMarkers();
},
onMapCreated: (GoogleMapController controller) async {
_controller.complete(controller);
checkMarkers();
},
);
}
google_maps_flutter is a developer preview at version 0.0.3. Please hang in there a bit until more functionality is introduced.

Flutter get coordinates from google maps

I use the package google_maps_flutter to use Google maps in my app. My problem is how to set a listener, show when I press in the map to get the coordination of this place. I don't find anything in documentation.
The only thing which I find is with controllerMap, which I use to set marker listener, is that it has a method,
.addListener(listener)
Any idea?
I have solved the problem using the onMarkerTapped callback methods below:
Note: mapController below is an instance of the GoogleMap Controller
mapController.**onMarkerTapped**.add((marker){
String title= marker.options.infoWindowText.title;
String latitude= marker.options.position.latitude.toString();
String longitude= marker.options.position.longitude.toString();
});
google map plugin has a lot of errors:), I prefer using this plugin : flutter_map
full example :
import 'package:location/location.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong/latlong.dart';
class ContactPage extends StatefulWidget {
#override
ContactPageState createState() => new ContactPageState();
}
class ContactPageState extends State<ContactPage>
with TickerProviderStateMixin {
static LatLng myLocation = new LatLng(51.5, -0.09);
#override
void initState() {
super.initState();
setState(() {
new LatLng(51.5, -0.09);
});
}
#override
Widget build(BuildContext context) {
Size screenSize = MediaQuery.of(context).size;
double heigh = screenSize.height;
TextStyle whiteStyle = new TextStyle(fontSize: 20.0, color: Colors.white);
return new Directionality(
textDirection: TextDirection.rtl,
child: new Container(
padding: new EdgeInsets.only(bottom: 10.0, left: 1.0, right: 1.0),
color: Colors.white,
child: new FlutterMap(
options: new MapOptions(
center: myLocation,
zoom: 15.0,
maxZoom: 15.0,
minZoom: 3.0,
onTap: _handleTap),
layers: [
new TileLayerOptions(
urlTemplate:
"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: ['a', 'b', 'c']),
new MarkerLayerOptions(markers: markers)
],
)
)),
);
}
_handleTap(LatLng point) {
setState(() {
myLocation = point;
});
}
}
This functionality is currently not available in version 2.0 of the google flutter plugin, however there are two pull requests that have added this functionality.
1121
941
Pull request 1121 has example code on how to use the tap functionality.
With the current documentation, I only made the following change to the example of #lionelsanou and #Pradeep given above:
String latitude= marker.values.first.position.toString();
String longitude= marker.values.last.position.toString();
and it worked for me.