Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Implementing Google-Maps in Flutter

What we will build ::

Before starting the blog let me tell you what you can learn from this blog/article:-

  1. You learn how to implement Google-Maps in your flutter app using flutter_google_maps package.
  2. How to fetch the live Geo-coordinates of the user location using location package.
  3. How to implement light and dark mode in google maps.
  4. How to move the maps camera bound form one geo-coord to another.
  5. You will learn how to add markers, polygons, directions, information about any geo-coord , displaying a dialog box containing information about the geo-coord ,clear polygon, direction, markers, etc.
  6. You will learn how to implement functionality into your flutter app, how to work with multiple packages.

Demo of our app: —


Introduction

Google Maps is a mapping service developed by Google. This tool provides us a lot of features that we can use in our daily lifestyle. Google Maps is highly effective and fast, provides us a lot of information in realtime.

Key Features:

  • :: Provide realtime information about traffic
  • :: Provide all possible routes between two points
  • :: Calculate accurate distance between two points
  • :: Provides us additional information about the location in which we are interested
  • :: Stores our travel history
  • :: Controls two-third of the online navigation market
  • :: Shopping app and websites actively uses maps to fasten their delivery process
  • :: Maps is highly used as a marketing tool

Table of content :

  1. Setting up project
  2. Install Packages
  3. Initialize Google maps
  4. Get the live location
  5. Displaying the google_map on screen
  6. Adding Widgets to implement functionality
  7. GitHub Link

Setting up Project :

  1. Follow the steps give in the documentation:

flutter_google_maps | Flutter Package
A Flutter plugin for integrating Google Maps in iOS, Android, and Web applications. It is a wrapper of…pub.dev

Do not forget to specify the API key in your android/app/src/main/AndroidManifest.xml file.

2. Add the location permission into the AndroidManifest.xml manifest outside of the application tag.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

3. Update your build.gradle file dependencies to this

dependencies {
classpath 'com.android.tools.build:gradle:3.3.0'
classpath 'com.google.gms:google-services:4.2.0'
}

4. minSdkVersion 21

Note: Last Two steps are used for location: package

Installing Package:

Install the following package:

flutter_google_maps | Flutter Package
A Flutter plugin for integrating Google Maps in iOS, Android, and Web applications. It is a wrapper of…pub.dev

location | Flutter Package
This plugin for Flutter handles getting a location on Android and iOS. It also provides callbacks when location is…pub.dev

hawk_fab_menu | Flutter Package
A floating action button menu that will pop up small fabs on top Add dependency in pubspec.yaml: hawk_fab_menu: ^0.2.2…pub.dev

Import package :

import 'package:flutter_google_maps/flutter_google_maps.dart';
import 'package:hawk_fab_menu/hawk_fab_menu.dart';
import 'package:location/location.dart';

Initialize Google maps :

Inside the main function, intit("your key") method is used to initialize the Google Map API.

void main() {
GoogleMap.init('your key');
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}

Get the live location:

To get the live location we will use the location package.

location | Flutter Package
This plugin for Flutter handles getting a location on Android and iOS. It also provides callbacks when the location is…pub.dev

getLocation() is a method used to get the live latitude and longitude . longitude , latitude are two variables used to store the geo-coordinates. getLocation is a method inside the Location() class which provides us the geo-coordinates. userLocation is used to provide the access the longitude ,latitude . We have used the try and catch method to display the error message if there is an error.

Future getLocation() async {
try {
var userLocation = await Location().getLocation();
setState(() {
longitude = userLocation.longitude;
latitude = userLocation.latitude;
});
} on Exception catch (e) {
print('Could not get location: ${e.toString()}');
}
}
double latitude;
double longitude;

Initializing the getLocation()

@override
void initState() {
getLocation();
super.initState();
}

Displaying the google_map on screen:

initializing Global keys

final _scaffoldKey = GlobalKey<ScaffoldState>();
final key = GlobalKey<GoogleMapStateBase>();

google map

flutter_google_maps provides us GoogleMap() widgets to display the map view on the screen. This widget has lots of properties that can be used to customize the map view. markers is the list of Marker() , used to display the markers on the screen. initialZoom is the initial zoom of the maps camera. initialPosition is the initial position of the map. It takes GeoCoord() widget. mapType specify the type of map type. mapStyle is the color combination of the map. Here I have added a functionality when the user will click on the map at any position the marker will we added to the map at that particular location.

onTap: (geo) {
setState(() {
longitude = geo.longitude;
latitude = geo.latitude;
});
_scaffoldKey.currentState.showSnackBar(SnackBar(
content: Text(geo?.toString()),
duration: const Duration(seconds: 2),
));
GoogleMap.of(key)
.addMarkerRaw(GeoCoord(latitude, longitude));
polygon.add(GeoCoord(latitude, longitude));
},

To do this we will need the coordinates of the point at which the user will click, so need to change the latitude ,longitude . Whenever the user clicks the screen snakeBar is also displayed that shows the values of geo-coord. Also to display the polygon we need some points that is why we used polygon.add(GeoCoord(latitude, longitude)); here polygon is the list of GeoCoord . To display the marker, GoogleMap class provides us addMarkerRaw() method.

GoogleMap(
key: key,
markers: {
Marker(
GeoCoord(latitude, longitude),
),
},
initialZoom: 12,
initialPosition: GeoCoord(latitude, longitude),
mapType: _mapType == null ? MapType.roadmap : _mapType,
mapStyle: _mapStyle,
interactive: true,
onTap: (geo) {
setState(() {
longitude = geo.longitude;
latitude = geo.latitude;
});
_scaffoldKey.currentState.showSnackBar(SnackBar(
content: Text(geo?.toString()),
duration: const Duration(seconds: 2),
));
GoogleMap.of(key)
.addMarkerRaw(GeoCoord(latitude, longitude));
polygon.add(GeoCoord(latitude, longitude));
},
mobilePreferences: const MobileMapPreferences(
trafficEnabled: true, zoomControlsEnabled: false),
webPreferences: WebMapPreferences(
fullscreenControl: true,
zoomControl: true,
),
),

Adding Widgets to implement functionality :

Screen Widgets

Changing the style of the map:

To change the style of the map I have used a CircleAvatar on the left of the screen, on tapping it displays a Dialog Box that shows the list of the type of the style of the map. On pressing any style it will change the map style.

List<MapType> mapType = [
MapType.hybrid,
MapType.roadmap,
MapType.satellite,
MapType.terrain,
MapType.none,
];
MapType _mapType ;
List<String> mapTypeName = [
"Hybrid",
"Roadmap",
"Satellite",
"Terrain",
"None"
];

The above variables are used to implement the functionality.

Positioned(
top: 15,
right: 20,
child: InkWell(
onTap: () {
showDialog(
context: context,
builder: (_) {
return AlertDialog(
title: Text("Map Style"),
content: Container(
height: mapType.length * 64.0,
width: 100,
child: ListView.builder(
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(mapTypeName[index]),
onTap: () {
setState(() {
_mapType = mapType[index];
});
Navigator.of(context).pop();
},
),
);
},
itemCount: mapType.length,
),
),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("CANCEL"),
)
],
);
});
},
child: CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
child: Icon(
Icons.filter_none,
color: Colors.blue,
),
),
))

Edit menu

To display the edit menu I have used an animated floatingActionButton .

body: HawkFabMenu(
items: [
HawkFabMenuItem(
label: 'Add Polygon',
ontap: () {
},
icon: Icon(
Icons.crop_square,
),
),
HawkFabMenuItem(
label: 'Info Demo',
ontap: () {
},
icon: Icon(Icons.pin_drop),
),
HawkFabMenuItem(
label: 'Directions',
ontap: () {
},
icon: Icon(Icons.directions),
),
],
body: _body
],
),
));

Add Polygon :

addPolygon() is a method that makes id and a List of GeoCoord() that connect each other to display a polygon on the map screen. editPolygon is used to edit the polygon.

ontap: () {
if (!_polygonAdded) {
GoogleMap.of(key).addPolygon(
'1',
polygon,
onTap: (polygonId) async {
await showDialog(
context: context,
builder: (context) => AlertDialog(
content: Text(
'This dialog was opened by tapping on the polygon!\n'
'Polygon ID is $polygonId',
),
actions: <Widget>[
FlatButton(
onPressed: Navigator.of(context).pop,
child: Text('CLOSE'),
),
],
),
);
},
);
} else {
GoogleMap.of(key).editPolygon(
'1',
polygon,
fillColor: Colors.purple,
strokeColor: Colors.purple,
);
}

setState(() => _polygonAdded = true);
},

Information Demo :

ontap: () {
GoogleMap.of(key).addMarkerRaw(
GeoCoord(latitude, longitude),
info: 'test info',
onInfoWindowTap: () async {
await showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text("Palace Info..."),
content:
Text('Latitude:$latitude\nLongitude:$longitude'),
actions: <Widget>[
FlatButton(
onPressed: Navigator.of(context).pop,
child: Text('CLOSE'),
),
],
),
);
},
);

},

Directions :

ontap: () {
GoogleMap.of(key).addDirection(
'San Francisco, CA',
'San Jose, CA',
startLabel: '1',
startInfo: 'San Francisco, CA',
endIcon:
'https://cdn0.iconfinder.com/data/icons/map-markers-2-1/512/xxx018-512.png',
endInfo: 'San Jose, CA',
);
},

Drawer

Light and dark mode :

To change the theme of the map GoogleMap class provides us changeMapStyle() method to change the style of the map. _darkMapStyle is a bool variable used to change the state of text, icon, and map style.

 ListTile(
leading: Icon(
Icons.wb_sunny,
color: _darkMapStyle ? Colors.deepOrange : Colors.black,
),
onTap: () {
Navigator.of(context).pop();
if (_darkMapStyle) {
GoogleMap.of(key).changeMapStyle(null);
_mapStyle = null;
} else {
GoogleMap.of(key).changeMapStyle(darkMapStyle);
_mapStyle = darkMapStyle;
}

setState(() => _darkMapStyle = !_darkMapStyle);
},
title:
Text(_darkMapStyle ? "Enable Light Mode" : "Enable Dark Mode"),
),

Move Camera Bound :

moveCameraBounds is a method used to move the maps camera from one

geo-coord to anothergeo-coord . It takes GeoCoordBounds() that is used to specify thenortheast, and southwest GeoCoord() . We are also displaying a marker on the specified location.

ListTile(
title: Text("Move camera bound"),
leading: Icon(
Icons.camera_enhance,
color: Colors.red,
),
onTap: () {
Navigator.of(context).pop();
final bounds = GeoCoordBounds(
northeast: GeoCoord(34.021307, -117.432317),
southwest: GeoCoord(33.835745, -117.712785),
);
GoogleMap.of(key).moveCameraBounds(bounds);
GoogleMap.of(key).addMarkerRaw(
GeoCoord(
(bounds.northeast.latitude + bounds.southwest.latitude) / 2,
(bounds.northeast.longitude + bounds.southwest.longitude) / 2,
),
onTap: (markerId) async {
await showDialog(
context: context,
builder: (context) => AlertDialog(
content: Text(
'This dialog was opened by tapping on the marker!\n'
'Marker ID is $markerId',
),
actions: <Widget>[
FlatButton(
onPressed: Navigator.of(context).pop,
child: Text('CLOSE'),
),
],
),
);
},
);
},
),

Clear Polygon :

clearPolygons() method clear all the drawn polygon on the map screen. polygon list is set to [] so that it also clear when all polygons are cleared.

ListTile(
title: Text("Clear Polygons"),
leading: Icon(
Icons.crop_square,
color: Colors.blue,
),
onTap: () {
GoogleMap.of(key).clearPolygons();
Navigator.of(context).pop();
setState(() {
polygon = [];
_polygonAdded = false;
});
},
),

Clear Marker :

clearMarker() method is used to clear all the markers from the maps.

ListTile(
title: Text("Clear Markers"),
leading: Icon(
Icons.location_off,
color: Colors.green,
),
onTap: () {
GoogleMap.of(key).clearMarkers();
Navigator.of(context).pop();
},
),

Clear Direction :

clearDirection()is used to clear all the directions from the map.

ListTile(
title: Text("Clear Directions"),
leading: Icon(
Icons.directions,
color: Colors.orangeAccent,
),
onTap: () {
GoogleMap.of(key).clearDirections();
Navigator.of(context).pop();
},
),

Github Link

flutter-devs/google_maps_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


If you find anything that could be improved please let me know, I would love to improve.💙

If this article has helped you a bit and found interesting please clap!👏


Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

www.flutterdevs.com

Leave comment

Your email address will not be published. Required fields are marked with *.