Industrial Training




Flutter Google Maps


A map is used to get information about the world simply and visually. It presents the world places by showing its shape and sizes, locations and distance between them. We can add a map in our application with the use of the Google Maps Flutter plugin. This plugin can automatically access the Google Maps servers, map display, and respond to user gestures. It also allows us to add markers to our map.


Why use Google Maps with Flutter?


Flutter developers prefer Google Maps for their application because they provide native performance for android and iOS both. It allows us to implement the code one time and permit them to run the code for both devices (android and iOS). Google Maps Flutter plugin is provided in the Google Map widget that supports initialCameraPosition, maptype and onMapCreated. We can set the position of the camera and marker in any place on the earth. We can design the marker according to our choice. It also comes with a zoom property in a cameraposition to provide the zooming in google map view on the initial page.
Let us see step by step to how to add Google Maps in Flutter application.
Step 1: Create a new project. Open this project in the IDE, navigate to the lib folder, and then open the pubspec.yaml file for setting the map.
Step 2: In pubspec.yaml file, we need to add the Google Maps Flutter plugin in the dependency section, which is available as google_maps_flutter on pub.dartlang.org. After adding a dependency, click on the get package link to import the library in the main.dart file.


dependencies:    
  flutter:    
    sdk: flutter    
  cupertino_icons: ^0.1.2    
  google_maps_flutter: ^0.5.21  

It ensures that we have left two spaces from the left side of a google_maps_flutter dependency while adding the dependencies.
Step 3: The next step is to get an API key for your project. If we are using an Android platform, then follow the instructions given on Maps SDK for Android: Get API Key. After creating the API key, add it to the application manifest file. We can find this file by navigating to android/app/src/main/AndroidManifest.xml as follows:


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

Step 4: Next, import the package in the dart file as below:


import 'package:google_maps_flutter/google_maps_flutter.dart';  

Step 5: Now, we are ready to add a GoogleMap widget to start creating a UI to display the map.

Example


Let us understand it with the help of an example.


import 'package:flutter/material.dart';  
import 'package:google_maps_flutter/google_maps_flutter.dart';  
  
void main() => runApp(MyApp());  
  
class MyApp extends StatefulWidget {  
  @override  
  _MyAppState createState() => _MyAppState();  
}  
  
class _MyAppState extends State< MyApp> {  
  GoogleMapController myController;  
  
  final LatLng _center = const LatLng(45.521563, -122.677433);  
  
  void _onMapCreated(GoogleMapController controller) {  
    myController = controller;  
  }  
  
  @override  
  Widget build(BuildContext context) {  
    return MaterialApp(  
      home: Scaffold(  
        appBar: AppBar(  
          title: Text('Flutter Maps Demo'),  
          backgroundColor: Colors.green,  
        ),  
        body: Stack(  
          children: < Widget>[  
            GoogleMap(  
              onMapCreated: _onMapCreated,  
              initialCameraPosition: CameraPosition(  
                target: _center,  
                zoom: 10.0,  
              ),  
            ),  
            Padding(  
              padding: const EdgeInsets.all(14.0),  
              child: Align(  
                alignment: Alignment.topRight,  
                child: FloatingActionButton(  
                  onPressed: () => print('You have pressed the button'),  
                  materialTapTargetSize: MaterialTapTargetSize.padded,  
                  backgroundColor: Colors.green,  
                  child: const Icon(Icons.map, size: 30.0),  
                ),  
              ),  
            ),  
          ],  
        ),  
      ),  
    );  
  }  
}  

In the above code, we have noticed these terms:
mapController: It is similar to other controllers that we had seen in Flutter. It controls all activities on the GoogleMap class. Here, it manages the camera function, such as position, animation, zooming, etc.
onMapCreated: It is a method called for creating a map and takes a MapController as an argument.
initialCameraPosition: It is a required parameter that sets the camera position from where we want to start. It allows us to set which part of the world we want to point on the map.
stack: It is used to place other Flutter widgets on top of the map widget.


Output:

When we run the app, it should return the UI of the screen as below screenshot:



How to change the map appearance?


We can change the map appearance such as normal view, satellite view, etc. using mapType property. This property allows developers to display the type of map tiles. The GoogleMap widget offers mainly five types of tiles, which are given below:


  • none: It does not display any map tiles.
  • normal: It displays the tiles on the map with traffic, labels and subtle terrain information.
  • satellite: It displays the satellite image (aerial photos) of the location.
  • terrain: It displays the specific physical features of an area of land (indicates type and height of terrain).
  • hybrid: It displays the satellite images with some labels or overlays.

We can do this by creating a variable _currentMapType in the above code to display the current map type and then add mapType: _currentMapType to the GoogleMap widget.


MapType _currentMapType = MapType.normal;  
  
@override  
Widget build(BuildContext context) {  
  return MaterialApp(  
    GoogleMap(  
      mapType: _currentMapType,  
    ),  
  );  
}   

Next, we have to add a method to modify the value of _currentMapType inside a setState() function call. This method will update the map appearance for matching with the new value of _currentMapType variable.


void _onMapTypeButtonPressed() {  
  setState(() {  
    _currentMapType = _currentMapType = = MapType.normal  
        ? MapType.satellite  
        : MapType.normal;  
  });  
}  

Finally, replace the onPressed property with _onMapTypeButtonPressed.


child: FloatingActionButton(  
  onPressed: _onMapTypeButtonPressed  
),  

Let us see the complete code to change the map appearance. Open the dart file and replace it with the below code:


import 'package:flutter/material.dart';  
import 'package:google_maps_flutter/google_maps_flutter.dart';  
  
void main() => runApp(MyApp());  
  
class MyApp extends StatefulWidget {  
  @override  
  _MyAppState createState() => _MyAppState();  
}  
  
class _MyAppState extends State< MyApp> {  
  GoogleMapController myController;  
  
  final LatLng _center = const LatLng(45.521563, -122.677433);  
  
  MapType _currentMapType = MapType.normal;  
  
  void _onMapTypeButtonPressed() {  
    setState(() {  
      _currentMapType = _currentMapType == MapType.normal  
          ? MapType.satellite  
          : MapType.normal;  
    });  
  }  
  
  void _onMapCreated(GoogleMapController controller) {  
    myController = controller;  
  }  
  
  @override  
  Widget build(BuildContext context) {  
    return MaterialApp(  
      home: Scaffold(  
        appBar: AppBar(  
          title: Text('Flutter Maps Demo'),  
          backgroundColor: Colors.green,  
        ),  
        body: Stack(  
          children: < Widget>[  
            GoogleMap(  
              onMapCreated: _onMapCreated,  
              initialCameraPosition: CameraPosition(  
                target: _center,  
                zoom: 10.0,  
              ),  
              mapType: _currentMapType  
            ),  
            Padding(  
              padding: const EdgeInsets.all(14.0),  
              child: Align(  
                alignment: Alignment.topRight,  
                child: FloatingActionButton(  
                  onPressed: _onMapTypeButtonPressed,  
                  materialTapTargetSize: MaterialTapTargetSize.padded,  
                  backgroundColor: Colors.green,  
                  child: const Icon(Icons.map, size: 30.0),  
                ),  
              ),  
            ),  
          ],  
        ),  
      ),  
    );  
  }  
}  

Output:

When we run the app, it should return the UI of the screen as below screenshot:



If we click on the map icon, we will get the satellite image of our specified location. See the below image:



How to add a marker on the map?


A marker identifies the location on the map. We can add a marker on a map by using the markers property inside the GoogleMap widget. Generally, the marker is shown when we move our camera from one location to another. For example, if we want to move from Poland to California, we can see a marker on that particular location when the camera moves to California.
We can add a marker by creating a variable _markers that will store the map's markers and then set this variable as the markers property in the GoogleMap widget.


final Set _markers = {};  
@override  
Widget build(BuildContext context) {  
  return MaterialApp(  
    GoogleMap(  
      markers: _markers,  
    ),  
  );  
}  


Next, it is required to track the current camera position on the map by adding the below code:


LatLng _currentMapPosition = _center;  
  
void _onCameraMove(CameraPosition position) {  
  _currentMapPosition = position.target;  
}  
  
@override  
Widget build(BuildContext context) {  
  return MaterialApp(  
    GoogleMap(  
      onCameraMove: _onCameraMove,  
    ),  
  );  
}   

Finally, we need to add a marker in the map by modifying the _markers inside a setState() function call.


void _onAddMarkerButtonPressed() {  
  setState(() {  
    _markers.add(Marker(  
      markerId: MarkerId(_lastMapPosition.toString()),  
      position: _currentMapPosition,  
      infoWindow: InfoWindow(  
        title: 'Nice Place'  
      ),  
      icon: BitmapDescriptor. defaultMarkerWithHue(BitmapDescriptor.hueViolet)  
    ));  
  });  
}  

Let us see the complete code to add marker to the map. Open the dart file and replace it with the below code:


import  'package:flutter/material.dart';  
import  'package:google_maps_flutter/google_maps_flutter.dart';  
  
void main() => runApp(MyApp());  
  
class MyApp extends StatefulWidget {  
  @override  
  _MyAppState createState() => _MyAppState();  
}  
  
class _MyAppState extends State< MyApp> {  
  GoogleMapController mapController;  
  static final LatLng _center = const LatLng(45.521563, -122.677433);  
  final Set< Marker> _markers = {};  
  LatLng _currentMapPosition = _center;  
  
  void _onAddMarkerButtonPressed() {  
    setState(() {  
      _markers.add(Marker(  
        markerId: MarkerId(_currentMapPosition.toString()),  
        position: _currentMapPosition,  
        infoWindow: InfoWindow(  
          title:  'Nice Place',  
          snippet:  'Welcome to Poland'  
        ),  
        icon: BitmapDescriptor.defaultMarker,  
      ));  
    });  
  }  
  
  void _onCameraMove(CameraPosition position) {  
    _currentMapPosition = position.target;  
  }  
  
  void _onMapCreated(GoogleMapController controller) {  
    mapController = controller;  
  }  
  
  @override  
  Widget build(BuildContext context) {  
    return MaterialApp(  
      home: Scaffold(  
        appBar: AppBar(  
          title: Text('Flutter Maps Demo'),  
          backgroundColor: Colors.green,  
        ),  
        body: Stack(  
          children: < Widget>[  
            GoogleMap(  
              onMapCreated: _onMapCreated,  
              initialCameraPosition: CameraPosition(  
                target: _center,  
                zoom: 10.0,  
              ),  
              markers: _markers,  
              onCameraMove: _onCameraMove  
            ),  
            Padding(  
              padding: const EdgeInsets.all(14.0),  
              child: Align(  
                alignment: Alignment.topRight,  
                child: FloatingActionButton(  
                  onPressed: _onAddMarkerButtonPressed,  
                  materialTapTargetSize: MaterialTapTargetSize.padded,  
                  backgroundColor: Colors.green,  
                  child: const Icon(Icons.map, size: 30.0),  
                ),  
              ),  
            ),  
          ],  
        ),  
      ),  
    );  
  }  
}  

Output:

Run the app, and we will get the UI of the screen as the first screenshot. When we click on the button, it displays the marker at the last location on the map. When we tapped the marker, the information is displayed that gives a title and snippet about the location.





Hi I am Pluto.