A Step-by-Step Guide to Integrating Google Maps in Flutter
In this tutorial I have explained the steps to integrate the google map in flutter through google_maps_flutter plugin.
Add the following dependency to your pubspec.yaml file:
dependencies:
google_maps_flutter: ^X.X.X
Get an API key from the Google Cloud Platform Console and add it to the AndroidManifest.xml file:
<meta-data android:name=”com.google.android.maps.v2.API_KEY” android:value=”YOUR_API_KEY”/>
Add the same API key to the ios/Runner/AppDelegate.swift file:
GMSServices.provideAPIKey(“YOUR_API_KEY”)
In your Dart code, import the package:
import ‘package:google_maps_flutter/google_maps_flutter.dart’;
Use the GoogleMap widget to display the map in your app. Here’s an example of how to use it:
GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(37.42796133580664, -122.085749655962),
zoom: 14.4746,
),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
To add markers to the map, you can use the Marker widget and add it as a child of the GoogleMap widget. Here’s an example:
Marker(
markerId: MarkerId(‘marker_1’),
position: LatLng(37.42796133580664, -122.085749655962),
infoWindow: InfoWindow(title: ‘My Marker’),
icon: BitmapDescriptor.defaultMarker,
)
To handle user interactions with the map, you can use the onMapCreated callback of the GoogleMap widget to get a reference to the GoogleMapController and use its methods to move the camera, add markers, etc. Here is an example of how to use GoogleMapController to move the camera to a specific location when a button is pressed:
final Completer<GoogleMapController> _controller = Completer();
…
RaisedButton(
onPressed: () async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(
target: LatLng(37.4219999,-122.0840575),
zoom: 16.0,
),
));
},
child: Text(‘Move Camera’),
)
This is a basic example and you can customize the map with different options and features provided by the package like adding polylines, customizing map styles, etc. You can find more detailed information and examples in the official documentation of the google_maps_flutter package: https://pub.dev/packages/google_maps_flutter
I hope this article was beneficial for you. Your appreciation is big motivation for me. Please comment your feedback and suggest a topic for next blog.
Thank you
Great Work
ReplyDelete