I am using google_maps_flutter package and I need to restrict the scrollable area of a map to a specific area. I have both the SW and NE corners, but I can't figure out how to do it.
I have tried the code below, but it's not working.
uniCampusSW and uniCampusNE are both LatLngs.
_userLocation == null // If user location has not been found
? Center(
// Display Progress Indicator
child: CircularProgressIndicator(
backgroundColor: UniColors.primaryColour[500],
),
)
: GoogleMap(
// Show Campus Map
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: 0.0),
scrollGesturesEnabled: true,
tiltGesturesEnabled: true,
trafficEnabled: false,
compassEnabled: true,
rotateGesturesEnabled: true,
myLocationEnabled: true,
mapType: _currentMapType,
zoomGesturesEnabled: true,
cameraTargetBounds: new CameraTargetBounds(
new LatLngBounds(
northeast: UniCampusNE,
southwest: UniCampusSW,
),
),
),
This is the error I get
/flutter (12525): The following assertion was thrown building TheMap(dirty, state: _TheMapState#a8840): I/flutter (12525): 'package:google_maps_flutter/src/location.dart': Failed assertion: line 68 pos 16: I/flutter (12525): 'southwest.latitude <= northeast.latitude': is not true.
thanks
Hello friends!
Solution with Null Safety
Note the error: 'southwest.latitude <= northeast.latitude': is not true.
According to documentation, link below:
https://pub.dev/documentation/google_maps_flutter_platform_interface/2.1.2/google_maps_flutter_platform_interface/LatLngBounds-class.html
It is necessary to check if these values are not static, as southwest.latitude must be less than or equal to northeast.latitude, and northeast.longitude must be less than or equal to southwest.longitude.
LatLng? UniCampusNE;
LatLng? UniCampusSW;
var nLat, nLon, sLat, sLon;
if (UniCampusSW!.latitude <= UniCampusNE!.latitude) {
sLat = UniCampusSW.latitude;
nLat = UniCampusNE.latitude;
}else{
sLat = UniCampusNE.latitude;
nLat = UniCampusSW.latitude;
}
if (UniCampusSW.longitude <= UniCampusNE.longitude) {
sLon = UniCampusSW.longitude;
nLon = UniCampusNE.longitude;
}else{
sLon = UniCampusNE.longitude;
nLon = UniCampusSW.longitude;
}
And in cameraTargetBounds: you can use the variables you created:
cameraTargetBounds: CameraTargetBounds(
LatLngBounds(
northeast: LatLng(nLat, nLon),
southwest: LatLng(sLat, sLon),
),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With