A Flutter application to demonstrate how to implement Google maps and its advanced options in a flutter app.

Last update: May 23, 2022

google_maps_flutter_example

A new Flutter application to demonstrate how to implement flutter google maps in a flutter application and perfoem advanced tasks on it.

Adding Map To the App

  1. Get an API key at https://cloud.google.com/maps-platform/.

  2. Enable Google Map SDK for each platform.

    • Go to Google Developers Console.
    • Choose the project that you want to enable Google Maps on.
    • Select the navigation menu and then select "Google Maps".
    • Select "APIs" under the Google Maps menu.
    • To enable Google Maps for Android, select "Maps SDK for Android" in the "Additional APIs" section, then select "ENABLE".
    • To enable Google Maps for iOS, select "Maps SDK for iOS" in the "Additional APIs" section, then select "ENABLE".
    • Make sure the APIs you enabled are under the "Enabled APIs" section.
  3. In android/app/src/main/AndroidManifest.xml inside Application tag add your key

">
<manifest ...
  android:name="com.google.android.geo.API_KEY"
               android:value="YOUR KEY HERE"/>
  1. In ios/Runner/AppDelegate.swift add the following lines
import UIKit
import Flutter
import GoogleMaps

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("YOUR KEY HERE")
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
  1. Use the GoogleMapsWidget.dart inside the lib/widget folder as normal widget and use it where you want.

Adding Custom Marker To the map

Adding normal marker

  1. Declare a Set of Markers that will be shown on the map
Set<Marker> _markers = Set<Marker>();
  1. Add the set of markers to GoogleMap widget
GoogleMap(
      markers: _markers,
  1. Update the set of markers after the map is created in onMapCreated
GoogleMap(
      onMapCreated: (GoogleMapController controller) {
              _controller.complete(controller);
              _setMapPins([LatLng(30.029585, 31.022356)]);
            }
  1. Using this function the map will be updated with the given markers on it
_setMapPins(List<LatLng> markersLocation) {
    _markers.clear();
    setState(() {
      markersLocation.forEach((markerLocation) {
        _markers.add(Marker(
          markerId: MarkerId(markerLocation.toString()),
          position: markerLocation,
        ));
      });
    });
  }

Customizing the markers

  1. Declare a BitmapDescriptor which will hold the customIcon
late BitmapDescriptor customIcon;
  1. Inside initState() Assign the needed png to the customIcon
@override
  void initState() {
    BitmapDescriptor.fromAssetImage(ImageConfiguration(size: Size(50, 50)),
            'assets/images/marker_car.png')
        .then((icon) {
      customIcon = icon;
    });
    super.initState();
  }
  1. Finally add the customIcon to the marker
Marker(
     markerId: MarkerId(markerLocation.toString()),
     position: markerLocation,
     icon: customIcon,
   )

Map Customization (Light/Dark mode)

Prepare the map styles

  1. Go to https://mapstyle.withgoogle.com/
  2. Choose the old version of the site by choosing No thanks, take me to the old style wizard
  3. You will find a lot of options, play with it until you get the desired style.
  4. Click Finish and a pop-up will show with the json code of your style, copy it and add it as a json file in your assets folder Don't forgot to mention it in your pubspec.yaml You can find two styles in the project's assets folder

Adding styles to the map

  1. Declare Strings that will hold your style's json and a bool to control which mode is shown on the map
bool mapDarkMode = true;
late String _darkMapStyle;
late String _lightMapStyle;
  1. In initState declare the styles
Future _loadMapStyles() async {
    _darkMapStyle = await rootBundle.loadString('assets/map_style/dark.json');
    _lightMapStyle = await rootBundle.loadString('assets/map_style/light.json');
  }
  1. After creating the map, set the style
onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
          _setMapPins([LatLng(30.029585, 31.022356)]);
          _setMapStyle();
        },
Future _setMapStyle() async {
    final controller = await _controller.future;
    if (mapDarkMode)
      controller.setMapStyle(_darkMapStyle);
    else
      controller.setMapStyle(_lightMapStyle);
  }
  1. To change the style we created a button on the map using the stack widget
Positioned(
   top: 100,
   right: 30,
   child: Container(
     height: 30,
     width: 30,
     child: IconButton(
       icon: Icon(
         mapDarkMode ? Icons.brightness_4 : Icons.brightness_5,
         color: Theme.of(context).primaryColor,
       ),
       onPressed: () {
         setState(() {
           mapDarkMode = !mapDarkMode;
           _setMapStyle();
         });
       },
     ),
   )),

Drawing routes

Activating Directions API

  1. Go to Google Developers Console.
  2. Choose the project that you want to enable Google Maps on.
  3. Select the navigation menu and then select "Google Maps".
  4. Select "APIs" under the Google Maps menu.
  5. Enable Google Directions, select "Directions API" in the "Additional APIs" section, then select "ENABLE".
  6. Make sure the APIs you enabled are under the "Enabled APIs" section.

Adding route to the map

  1. Declare your start and end points
final LatLng initialLatLng = LatLng(30.029585, 31.022356);
final LatLng destinationLatLng = LatLng(30.060567, 30.962413);
  1. Declare polyline and polylineCoordinates
Set<Polyline> _polyline = {};
List<LatLng> polylineCoordinates = [];
  1. After creating the map, set the polyline
onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
          _setMapPins([LatLng(30.029585, 31.022356)]);
          _setMapStyle();
          _addPolyLines();
        },
_addPolyLines() {
    setState(() {
      lat = (initialLatLng.latitude + destinationLatLng.latitude)/2;
      lng= (initialLatLng.longitude + destinationLatLng.longitude)/2;
      _moveCamera(13.0);
      _setPolyLines();
    });
  }
  1. To set polyline we send a get request to https://www.maps.googleapis.com/maps/api/directions/json with the start location, end location and the api key
final result = await MapRepository()
        .getRouteCoordinates(initialLatLng, destinationLatLng);
final route = result.data["routes"][0]["overview_polyline"]["points"];
  1. Then we translate the results to a polyline using the MapUtils
_polyline.add(Polyline(
    polylineId: PolylineId("tripRoute"),
    //pass any string here
    width: 3,
    geodesic: true,
    points: MapUtils.convertToLatLng(MapUtils.decodePoly(route)),
    color: Theme.of(context).primaryColor));

GitHub

https://github.com/heshamerfan97/flutter_google_maps_example
You might also like...

Flutter Advanced: TensorFlow Lite | Object Detection | YoloV2 | SSD Tutorial ||| SSD Tutorial

tflite_demo A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if t

Jun 16, 2022

A flutter app shows some meals, its ingredients and cooking steps

A flutter app shows some meals, its ingredients and cooking steps

meals_app A new Flutter project. This app shows some meals, its ingredients and cooking steps. Users can choose their meal by filtering their choice E

Nov 20, 2021

Flutter Package to implement Feedback System in your @Flutter project. Taking Feedback from users made Easy!

Flutter Package to implement Feedback System in your @Flutter project. Taking Feedback from users made Easy!

Flutter App Feedback Taking feedback from the user made easy! Simply integrate flutter_app_feedback package into your Flutter project and you are read

Nov 16, 2021

LogiFresh helps you build a login easily with a friendly design, and very flexible for its construction

LogiFresh helps you build a login easily with a friendly design, and very flexible for its construction

Login Fresh LogiFresh helps you build a login easily with a friendly design, and very flexible for its construction. Installation Follow the install i

Apr 20, 2022

Drishti is a simple mobile application created as a project for YIP KDISC and Google Devs Solution Challenge

Drishti is a simple mobile application created as a project for YIP KDISC and Google Devs Solution Challenge

Drishti is a simple mobile application created as a project for YIP KDISC and Google Devs Solution Challenge. This app aims to make reporting and spreading the news of accidents and dangers easier and effective.

Mar 24, 2022

Simple application for tracking weight. See Google Play for more details about this app!

WeightTracker Simple application for tracking weight. See Google Play for more details about this app! Getting started To build the app you need to cr

Jun 23, 2022

Shopping App developed using Flutter and Dart making use of Provider, Carousel Library, Google FireStore

Shopping App developed using Flutter and Dart making use of Provider, Carousel Library, Google FireStore. It's featuring standard modern shopping app UI

Jan 7, 2022

Flutter Google Sheets Example and Neumorphic Design

Flutter Google Sheets Example and Neumorphic Design

Flutter Google Sheets Example and Neumorphic Design Google Sheet is a web-based spreadsheet application created by Google. Google Sheet allows collabo

May 18, 2022

A News app that provides users with the outmost user experiance built with Google's flutter

A News app that provides users with the outmost user experiance built with Google's flutter

A News app that provides users with the outmost user experiance built with Google's flutter

Jun 5, 2022

Related

Movies Mobile Application to demonstrate Network calls in Flutter using with Chopper library
Movies Mobile Application to demonstrate Network calls in Flutter using with Chopper library

Movies Mobile Application to demonstrate Network calls in Flutter using with Chopper library. For API TMDB API console is used.

Feb 15, 2022
In this Project I will demonstrate you the power of firebase remote config :)

power-of-firebase-remote-config In this Project I will demonstrate you the power of firebase remote config :) This project serves as a template. Purpo

Mar 7, 2022
Demonstrate how to easily program Android apps on Gitpod
Demonstrate how to easily program Android apps on Gitpod

Developing Android apps on Gitpod This project is intended to demonstrate how to easily program Android apps on Gitpod. It is based on this guide and

Jan 27, 2022
Fingerprint Local Auth App Flutter Advanced Face ID & Touch ID/Fingerprint Local Auth App

flutterlocalauth A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started

Mar 2, 2022
Attempt to implement better scrolling for Flutter Web and Desktop. Includes keyboard, MButton and custom mouse wheel scrolling.
Attempt to implement better scrolling for Flutter Web and Desktop. Includes keyboard, MButton and custom mouse wheel scrolling.

An attempt to implement better scrolling for Flutter Web and Desktop. Includes keyboard, MButton and custom mouse wheel scrolling. Getting started Exa

Jun 13, 2022
Flutter Advanced: ARCore Tutorial | Sceneform | Exploring New Possibilities || Exploring New Possibilities

flutter_ar A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

Jun 16, 2022
Flutter Advanced: PDF Viewer Tutorial Android & IOS | From URL & Asset | From URL & Asset

flutterpdfview A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started i

May 22, 2022
Flutter Advanced: Auto Create Models from JSON | Serializable | Serializable

flutterautomodel A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started

Jan 28, 2022
Flutter Advanced: Background Fetch | Run code in the background Android & iOS | Run code in the background Android & iOS

flutterbackground A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you starte

Mar 2, 2022