Flutter: Add a Google maps widget
Easily add a map in android, iOS and web platforms
Goal
Almost every app needs at some point show a map with more or less info. In this story we are going to see how easy is nowadays to add a google maps widget in our project.
From google maps package version 2.3.0, the integration of the three main platforms have improved a lot, avoiding past problems in the web platform. For that reason, lets go to include the widget in a few steps!
Step 1
To show our map, first of all, google_maps_flutter package have to be included in the project pubspec.yaml file:
flutter pub add google_maps_flutter
Step 2
Once the dependency is added, next step is to include the widget in our screen. In our sample case we have decided to add it into a column along with other components, but you can use it as a full screen reader.
// We should import the package first
import 'package:google_maps_flutter/google_maps_flutter.dart';
Step 3
In this basic sample we need to create some variables to manage the center point of the map and the map controller
/// Controller for our map *
late GoogleMapController mapController;
/// Starting center point *
final LatLng _center = const LatLng(37.98732649165334, -1.1284812420549881);
/// Assign map controller after creation*
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
}
Step 4
Finally we just have to set the map with one marker in place. As we said, in our sample it is a widget besides others, but maybe you need to make it full screen:
// Google maps
Container(
height: 400,
padding: const EdgeInsets.all(10.0),
child: GoogleMap(
onMapCreated: _onMapCreated,
zoomControlsEnabled: true,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 16.0,
),
markers: <Marker>{
Marker(
draggable: true,
markerId: const MarkerId("1"),
position: _center,
icon: BitmapDescriptor.defaultMarker,
)
},
),
),
Thank you for reading until the end. I hope this story help you :)
Mentions
This article is based on the official flutter documentation which is always updated. I recommend to check it in order to continue with more advanced messaging formats:
https://codelabs.developers.google.com/codelabs/google-maps-in-flutter#0