This article shows you step-by-step how to add a Google Map widget to your Flutter application. Here’s what you’re going to build today:

Setup

The first step is to add the Google Maps Flutter plugin as a dependency in the pubspec.yaml file. The package is available as google_maps_flutter , location and http on pub.dartlang.org.

Once you do that, you need to run flutter packages get.

The next step is getting an API key for both Android and iOS.

For android

<manifest ...  
<application ...
<meta-data android:name="com.google.android.geo.API_KEY" android:value="YOUR ANDROID API KEY HERE"/>

For ios

#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
// Add the GoogleMaps
import.#import "GoogleMaps/GoogleMaps.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ // Add the following line with your API key.
[GMSServices provideAPIKey:@"YOUR IOS API KEY HERE"]; [GeneratedPluginRegistrant registerWithRegistry:self];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end

Adding a GoogleMap widget

Completer<GoogleMapController> _controller = Completer();  static const LatLng _center = const LatLng(45.521563, -122.677433);void _onMapCreated(GoogleMapController controller) {   
_controller.complete(controller);
}

after creating _onMapCreated and getting latlng u simple create a Scaffold and in place the GoogleMap in body of Scaffold,

body: GoogleMap(
onMapCreated: _onMapCreated, initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
),

Add Marker

final Set<Marker> _markers = {};void _onAddMarkerButtonPressed() {
setState(() {
_markers.add(Marker(
markerId: MarkerId("111"),
position: latLng,
icon: BitmapDescriptor.defaultMarker,
));
});
}
and simply set this marker on,
>> markers: _markers,
in GoogleMap which is we are place in Sccaffold body.

Getting Live Location

for getting user live location you need to simply add a location package. After adding this package you need

static LatLng latLng;
LocationData currentLocation;
getLocation() async {
var location = new Location(); location.onLocationChanged().listen(( currentLocation) { print(currentLocation.latitude); print(currentLocation.longitude);
setState(() {
latLng = LatLng(currentLocation.latitude, currentLocation.longitude);
});
print("getLocation:$latLng");
loading = false;
});
}

Call this getLocation() in your initState method. Which gives you, your current location or Lattitude and longitude.

Add Current location on Google Map

Now the latLng we are get now set it on the initialCameraPosition which is built-in method of GoogleMap

initialCameraPosition: CameraPosition(
target: latLng,
zoom: 14.4746,
),

Here we are now we see map with our current location

xxx
Current position of user

Now the quetion is that how to draw route from source to destination ??

So lets talk about that, here i created a simple method for reach to the destination. In that method i calling an api whose parameters are source latlng and destination latlng.

for showing a route on map we need of polyline so we get polyline for draw and show the route. In that Polyline we gives a width, changes the colour of that line.

final Set<Polyline> _polyLines = {};
Set<Polyline> get polyLines => _polyLines;
void createRoute(String encondedPoly) {
_polyLines.add(Polyline(
polylineId: PolylineId(latLng.toString()),
width: 4,
points: _convertToLatLng(_decodePoly(encondedPoly)), color: Colors.red));
}

From this createRoute method we simply draw polyline from our source to destination. In this method _convertToLatLng() method is used for converting a points into lat and long and then pass to createRoute() method.

List<LatLng> _convertToLatLng(List points) {
List<LatLng> result = <LatLng>[];
for (int i = 0; i < points.length; i++) {
if (i % 2 != 0) {
result.add(LatLng(points[i - 1], points[i]));
}
}
return result;
}

The _decodePoly method is used for decoding our points into expected lattitude and longitude.

List _decodePoly(String poly) {
var list = poly.codeUnits;
var lList = new List();
int index = 0;
int len = poly.length;
int c = 0;
do {
var shift = 0;
int result = 0;
do {
c = list[index] - 63;
result |= (c & 0x1F) << (shift * 5);
index++;
shift++;
}
while (c >= 32);
if (result & 1 == 1) {
result = ~result;
}
var result1 = (result >> 1) * 0.00001;
lList.add(result1);
} while (index < len);
for (var i = 2; i < lList.length; i++)
lList[i] += lList[i - 2];
print(lList.toString());
return l List;
}

Now we get both source latLng and destination latLng. So now quetion is HOW TO PASS THIS POINTS TO MAP AND HOW TO GET EXPECTED OUTPUT??

The solution is very easy we have already created a GoogleMapsServices class. In that class we simply get an api for passing the latLng variable of source and destination. Now we simply a object of that class and calling a method of this class.

void sendRequest() async {
LatLng destination = LatLng(20.008751, 73.780037);
String route = await _googleMapsServices.getRouteCoordinates( latLng, destination);
createRoute(route);
_addMarker(destination,"KTHM Collage");
}

here, we created a simply class of object.

GoogleMapsServices _googleMapsServices = GoogleMapsServices();

And call getRouteCoordinates() method which is already defined in GoogleMapsServices() class. Now call this sendRequest() method on onPress of button. And finally your route is drawn.

What else can you do?

Once again, the GoogleMap widget is just a widget. This means you can place widgets on top of it (like you just did), you can place it inside other widgets (like a ListView, for example), or if you’re feeling a bit wild, you could even place it in a Transform widget*.

That’s it for this article! I hope you enjoyed it, and leave a few claps if you did. Follow me for more Flutter articles and comment for any feedback you might have about this article.

My source code is available at

Some of my other articles

--

--