Flutter

How to add Google Maps in Flutter

By January 15, 2020 April 20th, 2020 No Comments

Simple steps to include Google Maps in your Flutter project.

First of all you need to add the google_maps_flutter in your project.

dependencies:
  flutter:
    sdk: flutter

  google_maps_flutter: ^0.5.21+15

 

Add Google Maps Key

  1. Open Google Cloud Platform
  2. Enable Api for “Maps SDK Android” and “Maps SDK iOS”.
  3. Retrieve the Keys from the credentials section

 

The key look something like this:

AIzaSyBWYo………………….hxkPLI9nP9n0

Setup Android

Find the AndroidManifest.xml

and add the following lines to include the Api key:

<application ...

<meta-data android:name="com.google.android.maps.v2.API_KEY"
            android:value="YOUR KEY"/>

..rest of the application..

</application>

That’s it! This is enough to make work the google widget in our Flutter App.

Setup iOS

Let’s setup the iOS application.

Open the file AppDelegate in the generated folder ios.

and add the code so the file looks like this one:

import UIKit
import Flutter
import GoogleMaps

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("AIzaSyBWYoCXoSxonHenZADYmShxkPLId9nP9n0") <--Invalid key, add your key similar to this
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

 

Also, you need to add in the info.plist file a new key:

<key>io.flutter.embedded_views_preview</key>
<string>YES</string>

 

Create Google Map Widget

Up to now we have just setup the environment to make all things work.

But our App is still empty since we do not use any map widget in our App.

GoogleMap: Main widget to display the map.

It is preatty configurable, here there are some of the required and optional parameters:

initialCameraPosition: An object CameraPosition needs to be provided. This indicates where the map will be positioned at the beginning.
onMapCreated: Listener need to know when the map is loaded.
mapType: Type of map, Hybrid, Normal, Terrain.
onTap: Listener to handle the taps on the map
onLongPress: Listener to handle the long press on the map.

First of all, we need to define a Completer so we will know when the map is loaded.

Completer<GoogleMapController> _controller = Completer();

Next step is to create the GoogleMap widget. We use the minimum parameters needed to instantiate it.

GoogleMap(
    initialCameraPosition: CameraPosition(target: LatLng(40, 30),);,
    mapType: MapType.normal,
    onMapCreated: (GoogleMapController controller) {
      _controller.complete(controller);
    },
  ),

 

You can easily place this widget as the main widget in your App as follows:

class MyMap extends StatefulWidget {
  @override
  State<MyMap> createState() => MyMapState();
}

class MyMapState extends State<MyMap> {
  Completer<GoogleMapController> _controller = Completer();

  static final CameraPosition _kInitLocation = CameraPosition(
    target: LatLng(41.39, 2.08),
    zoom: 14,
  );

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: GoogleMap(
        mapType: MapType.normal,
        initialCameraPosition: _kInitLocation,
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
      )
    );
  }
}

 

CameraPosition

  • target: Location of the map, is a LatLng(double, double)
  • bearing: Rotation from the north axis.
  • tilt: Angle used to represent the map (inclination),
  • zoom: Zoom out used.

MapType

normal

MapType.normal

sattelite

MayType.sattelite

hybrid

MapType.hybrid

terrain

MapType.terrain

Everything is a widget

And remember everything is a widget. Of course GoogleMap is also a widget.

Can you imagine what you can do with this?

With a very simple code I can scale the map and integrate it in any part of my UI.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GoogleMap Example',
      home: MyHomePage()
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
   return Stack(
      alignment: Alignment.center,
      children: <Widget>[
        Image.asset("assets/smartphone.jpg"),
        Positioned(
            top: MediaQuery.of(context).size.height /2 -96,
            left: MediaQuery.of(context).size.width /2 -41,
            child:ConstrainedBox(constraints: BoxConstraints(maxHeight: 168,maxWidth: 94) ,child:MyMap(),))
      ],);
  }
}

 

Simple right? I hope this little tutorial has been helpful to you!

If you have suggestions, comments, or you have seen any error. Please leave a comment! I will be very happy to receive some feedback.

January 1, 2021 in Articles, Business

Some thoughts and advice for freelancers

Here we are, yet another year on my own, it's been more than 2 years since I had decided to become a company of one, meaning I adapt to small…
Read More
November 11, 2020 in Flutter

How to implement SwipeRefreshLayout on Flutter

If you are wondering what is the equivalent of SwipeRefreshLayout in Flutter. Here is the answer: RefreshIndicator. And it is much more simple than its brother in Android. Let's have…
Read More
November 11, 2020 in Flutter

Parse String to int or double in Dart Flutter

How to parse a String into an Int in Dart. String myString = "1"; int.parse(myString); Remember to use try and catch since it can throw FormatException. Or you can try…
Read More
November 10, 2020 in Uncategorized

How to test Cubit in Flutter

Test Cubit I am going to write this post as short as possible. So I am going to cut the talking about why creating test cubit on Flutter is good…
Read More
Ernie

Author Ernie

More posts by Ernie