Reputation: 455
I want to automatically center the Google Map of the plugin google_maps_flutter
in Flutter with a list of markers. The markers are returned from an API and I would like to open the Google Map with a CameraPosition
containing all markers with some padding. How would I do that?
I've used that example to integrate the map.
Upvotes: 0
Views: 435
Reputation: 980
Here is a sample to show 2 markers. You can get the south west and north east locations from markers list.
GoogleMap(
initialCameraPosition: _initPosition,
onMapCreated: (GoogleMapController controller) {
//Camera Update to include 2 marker location
LatLngBounds bound;
if (loc1.lat > loc2.lat &&
loc1.lng > loc2.lng) {
bound = LatLngBounds(
southwest: LatLng(loc2.lat, loc2.lng),
northeast: LatLng(loc1.lat, loc1.lng),
);
} else if (loc1.lng > loc2.lng) {
bound = LatLngBounds(
southwest: LatLng(loc1.lat, loc2.lng),
northeast: LatLng(loc2.lat, loc1.lng));
} else if (loc1.lat > loc2.lat) {
bound = LatLngBounds(
southwest: LatLng(loc2.lat, loc1.lng),
northeast: LatLng(loc1.lat, loc2.lng));
} else {
bound = LatLngBounds(
southwest: LatLng(loc1.lat, loc1.lng),
northeast: LatLng(loc2.lat, loc2.lng),
);
}
CameraUpdate u2 =
CameraUpdate.newLatLngBounds(bound, 50);
Future.delayed(Duration(milliseconds: 500))
.then((value) => controller.animateCamera(u2));
},
)
Upvotes: 1