Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Prerequisite
3.
Getting Started
3.1.
Adding Google Maps Flutter plugin as a dependency
3.2.
Configuring iOS platform
3.3.
Configuring Android minSDK
4.
Adding Google Maps
4.1.
Adding an API key for Android
4.2.
Adding an API key for iOS
4.3.
Adding an API key for a Web app
4.4.
Putting a map on the screen
4.5.
Running the App
5.
Adding Google on the Map
5.1.
Parsing JSON with code generation
6.
Output
7.
Frequently Asked Questions
7.1.
What is Flutter?
7.2.
What is a JSON file?
7.3.
What is an API?
7.4.
What is Dart?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Working with Google Maps

Author Nagendra
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Mobile applications are integrating location-aware services into your life virtually every day. The Google Maps API can be used to integrate these services into your applications. Among other things, it allows you to display a map, change its properties, and render markers of places at their geo-location. You can use the Google Maps Flutter plugin to add maps to your application that are based on Google Maps data. The plugin takes care of accessing Google Maps servers, displaying maps, and responding to user actions like clicks and drags. Markers can also be added to your maps. These objects give the user more information about map places and allow them to interact with the map. Without further ado, let's get started.

Prerequisite

You'll require two software: the Flutter SDK and an Editor. This application can run on any of the following devices:

  • A physical device that is linked to your computer and set to development mode (Android or iOS).
  • iOS Simulator. (Xcode tools must be installed.)
  • Android Emulator. (This necessitates the use of Android Studio)
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Getting Started

The most straightforward approach to getting started with Flutter is to utilise the flutter command-line tool to generate all of the necessary code for a quick start.

Command:

$ flutter create google_maps_in_flutter

In order to run your application, type:


Command:

$ cd google_maps_in_flutter
  $ flutter run

 

google_maps_in_flutter/lib/main.dart contains the entry-point code for your application.

Adding Google Maps Flutter plugin as a dependency

Using Pub packages, you can easily extend the functionality of a Flutter app. The following command will introduce the Google Maps Flutter plugin.

Command:

$ cd google_maps_in_flutter
$ flutter pub add google_maps_flutter

Configuring iOS platform

A platform minimum of iOS 11 is required to get the newest version of the Google Maps SDK on iOS. Make the following changes to the ios/Podfile (The Podfile is a specification that outlines the targets of one or more Xcode projects' dependencies.):

ENV['COCOAPODS_DISABLE_STATS'] = 'true'

Configuring Android minSDK

On Android platform, setting the minSDK to 20 is required to use Google Maps SDK. Make the following changes to the android/app/build.gradle file.

Code:

android {
    defaultConfig {
        applicationId "com.example.google_maps_in_flutter"
        minSdkVersion 20 
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }
}

Adding Google Maps

To use the Google Maps in your Flutter app, you'll need to create an API project using the Google Maps Platform and use the Using API key from the Maps SDK for Android, Maps SDK for iOS, and Maps JavaScript API. Follow the steps below to configure both Android and iOS apps once you have your API credentials.

Adding an API key for Android

Edit the AndroidManifest.xml file present in android/app/src/main to add an API key to the app. Inside the application node, add a single meta-data entry holding the API key created in the previous step.
Code:

<manifest xmlns:android= "http://schemas.android.com/apk/res/android"
    package= "com.example.google_maps_in_flutter">
    <application
        android:label="google_maps_in_flutter"
        android:icon="@mipmap/ic_launcher">

        <!-- TODO:Here you can enter your Google Maps API key. -->
        <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="YOUR-KEY-HERE"/>

        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

Adding an API key for iOS

Edit the AppDelegate.swift file under ios/Runner to add an API key to the iOS app. Unlike Android, introducing an API key on iOS necessitates changes to the Runner app's source code. The AppDelegate is a singleton that is created during the app's initialization.
Make two modifications to this file. Add a #import statement to pull in the Google Maps headers, and then call the GMSServices singleton's provideAPIKey() method. This API key allows Google Maps to serve map tiles appropriately.

Code:

import UIKit
import Flutter
import GoogleMaps // Add this import

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)

    // TODO: Add your Google Maps API key
    GMSServices.provideAPIKey("YOUR-API-KEY")

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Adding an API key for a Web app

Edit the index.html file on the web to add an API key to the Web app. In the head area, including a reference to the Maps JavaScript script, along with your API key.


Code:

<head>
  <base href="/">

  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">

  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="google_maps_in_flutter">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">

  <!-- TODO: Here you can enter your Google Maps API key. -->
  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR-KEY-HERE"></script>

  <title>google_maps_in_flutter</title>
  <link rel="manifest" href="manifest.json">
</head>

Putting a map on the screen

It's now time to get a map on the computer screen. Make the following changes to lib/main.dart:

Code:

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late GoogleMapController mapController;
//Assigning the latitude and Longitude
  final LatLng _center = const LatLng(45.521563, -122.677433);
//Checking the content on the Map
  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Maps Sample App'),
          backgroundColor: Colors.green[700],
        ),
        body: GoogleMap(
          onMapCreated: _onMapCreated,
          initialCameraPosition: CameraPosition(
            target: _center,
            zoom: 11.0,
          ),
        ),
      ),
    );
  }
}

Running the App

To see a single map view centered on Portland, open the Flutter app on iOS or Android. Alternatively, you can use an Android emulator or an iOS simulator to get started. Feel free to change the map's centre to symbolise your hometown or another important location to you.

Command:

$ flutter run

 

Output:

Source

Adding Google on the Map

Google has offices across North America, Latin America, Europe, Asia Pacific, Africa, and the Middle East, among other places. If you look into these maps further, you'll notice that they include an easy-to-use API endpoint for giving office location data in JSON format. In this phase, you will plot the locations of these offices on a map. To parse JSON, you'll employ code generation in this phase.

As seen below, add three new Flutter dependencies to the project. To begin, install the http package to make HTTP requests more easily.

$ flutter pub add http

Next, declare an object structure for expressing JSON documents using json_serializable.

$ flutter pub add json_serializable

Finally, create a development-time dependency for build_runner. This will be used to generate code in the next phase.

$ flutter pub add --dev build_runner

Parsing JSON with code generation

Create a locations.dart file in the lib/src directory and explain the structure of the returned JSON data as follows:

Code:

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:json_annotation/json_annotation.dart';
import 'package:flutter/services.dart' show rootBundle;

part 'locations.g.dart';

@JsonSerializable()
class LatLng {
  LatLng({
    required this.lat,
    required this.lng,
  });

  factory LatLng.fromJson(Map<String, dynamic> json) => _$LatLngFromJson(json);
  Map<String, dynamic> toJson() => _$LatLngToJson(this);

  final double lat;
  final double lng;
}

@JsonSerializable()
class Region {
  Region({
    required this.coords,
    required this.id,
    required this.name,
    required this.zoom,
  });

  factory Region.fromJson(Map<String, dynamic> json) => _$RegionFromJson(json);
  Map<String, dynamic> toJson() => _$RegionToJson(this);

  final LatLng coords;
  final String id;
  final String name;
  final double zoom;
}

@JsonSerializable()
class Office {
  Office({
    required this.address,
    required this.id,
    required this.image,
    required this.lat,
    required this.lng,
    required this.name,
    required this.phone,
    required this.region,
  });

  factory Office.fromJson(Map<String, dynamic> json) => _$OfficeFromJson(json);
  Map<String, dynamic> toJson() => _$OfficeToJson(this);

  final String address;
  final String id;
  final String image;
  final double lat;
  final double lng;
  final String name;
  final String phone;
  final String region;
}

@JsonSerializable()
class Locations {
  Locations({
    required this.offices,
    required this.regions,
  });

  factory Locations.fromJson(Map<String, dynamic> json) =>
      _$LocationsFromJson(json);
  Map<String, dynamic> toJson() => _$LocationsToJson(this);

  final List<Office> offices;
  final List<Region> regions;
}

Future<Locations> getGoogleOffices() async {
  const googleLocationsURL = 'https://about.google/static/data/locations.json';

  // Get a list of Google offices' locations.
  try {
//the try block
    final response = await http.get(Uri.parse(googleLocationsURL));
//Checking for the response Code
    if (response.statusCode == 200) {
      return Locations.fromJson(json.decode(response.body));
    }
  }
//Catch Block
catch (exp) {
    print(exp);
  }

//If the above HTTP request fails, this will be used as a fallback.
  return Locations.fromJson(
    json.decode(
      await rootBundle.loadString('assets/locations.json'),
    ),
  );
}

Because it refers to a nonexistent sibling file, locations.g.dart, your IDE (if you're using one) should display some red squiggles once you've added this code. This file translates between named objects and untyped JSON formats. Run the build_runner command to make it:

$ flutter pub run build_runner build --delete-conflicting-outputs

Your code should now be able to analyse correctly once more. The fallback locations should be included next. The getGoogleOffices function uses a json file. Because the static data fetched in this function is delivered without CORS headers, it will fail to load in a web browser. CORS headers aren't required for the Android and iOS Flutter apps, but mobile data access can be difficult at best. 

Add the asset file to the flutter section of your pubspec.yaml file now that you've downloaded it.

flutter:
  uses-material-design: true
  assets:
    - assets/locations.json

Modify the main.dart file to request map data, and then add offices to the map using the information returned:

Code:

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'src/locations.dart' as locations;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final Map<String, Marker> _markers = {};
  Future<void> _onMapCreated(GoogleMapController controller) async {
    final googleOffices = await locations.getGoogleOffices();
    setState(() {
      _markers.clear();
      for (final office in googleOffices.offices) {
        final marker = Marker(
          markerId: MarkerId(office.name),
          position: LatLng(office.lat, office.lng),
          infoWindow: InfoWindow(
            title: office.name,
            snippet: office.address,
          ),
        );
        _markers[office.name] = marker;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Google Office Locations'),
          backgroundColor: Colors.green[700],
        ),
        body: GoogleMap(
          onMapCreated: _onMapCreated,
          initialCameraPosition: const CameraPosition(
            target: LatLng(0, 0),
            zoom: 2,
          ),
          markers: _markers.values.toSet(),
        ),
      ),
    );
  }
}

This code does the following tasks:

  • It uses the JSON parsing code in _onMapCreated and waits till it's loaded. The given data is then used to build Markers within a setState() callback
  • SetState() flags Flutter to repaint the screen when the app receives new markers, prompting the office locations to appear.
  • The markers are saved in a GoogleMap widget-linked Map. The markers will be linked to the correct map as a result of this. Of course, you might have numerous maps with different markers on each one.

Congratulations!! You've created a Flutter app that includes a Google Map! In addition, you've used a JSON Web Service.

Output

You will get the output as :

Source

Frequently Asked Questions

What is Flutter?

Flutter is a Google open-source framework that allows you to create beautiful, natively built, multi-platform apps from a single codebase.

What is a JSON file?

JSON (JavaScript Object Notation) is a text-based standard for encoding structured data that is based on JavaScript object syntax. It's often used in web applications to send data.

What is an API?

An API is a set of programming codes that allows data to be transferred between two software products.

What is Dart?

Dart is a client-side programming language that may be used to create web and mobile apps. It can be used to create both server and desktop apps.

Conclusion

In this article, we have extensively discussed the details of creating a mobile app using the Flutter SDK, which includes a Google Map and using the services of Google Maps. We have also discussed its implementation in Android, IOS, and Web App. 

We hope that this blog has helped you enhance your knowledge regarding working with google maps on Flutter, and if you would like to learn more, check out our articles on Android Development. You can refer to our guided paths on the Coding Ninjas Studio platform to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. To practice and improve yourself in the interview, you can also check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews

 

Check out the Google Interview Experience to learn about Google’s hiring process.


Do upvote our blog to help other ninjas grow. 

Happy Coding!!

Live masterclass