How to integrate google map in flutter?
To integrate Google Maps into a Flutter app, you can use the google_maps_flutter package.
Here are the steps to use it:
- Add the google_maps_flutter dependency to your pubspec.yaml file.
dependencies:
google_maps_flutter: ^0.7.0
- Obtain an API key from the Google Cloud Console.
- Add the API key to your AndroidManifest.xml file (for Android) and your Info.plist file (for iOS).
- Import the package into your Dart file.
import 'package:google_maps_flutter/google_maps_flutter.dart';
Use the GoogleMap widget in your app, providing the required MapController and CameraPosition objects.
GoogleMap(
mapType: MapType.normal,
initialCameraPosition: CameraPosition(
target: LatLng(37.42796133580664, -122.085749655962),
zoom: 14.4746,
),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
Example:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class MapSample extends StatefulWidget {
@override
State<MapSample> createState() => MapSampleState();
}
class MapSampleState extends State<MapSample> {
Completer<GoogleMapController> _controller = Completer();
static final CameraPosition _kGooglePlex = CameraPosition(
target: LatLng(37.42796133580664, -122.085749655962),
zoom: 14.4746,
);
@override
Widget build(BuildContext context) {
return GoogleMap(
mapType: MapType.normal,
initialCameraPosition: _kGooglePlex,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
);
}
}
In this example, the MapSample widget displays a normal-type Google Map with the initial camera position set to _kGooglePlex. Once the map is created, the Completer object _controller is used to complete the GoogleMapController. The onMapCreated callback is triggered when the map is ready and passes the GoogleMapController to the _controller.complete method to meet the future.
Comments
Post a Comment