Play all audios:
THE BEST PART: You can do it without a billing account in Google Cloud Console!!! > We are going to get the points from openrouteservice API, connect > them and place them on the map!
> In this post I’m going to discuss about the steps of drawing route > direction line between two locations on a Flutter app using GOOGLE > MAPS FLUTTER PACKAGE , HTTP PACKAGE and
an open source route API > provided by OPENROUTESERVICES. We don’t have to enable google > direction API .Google Direction API actually needs a billing account > and if you don’t
have one, this post is for you! I assume you > already have experience of the maps set up in flutter project using > the Google Maps Flutter Package, HTTP Package and you’re familiar
> with Google Maps API key. WHAT IS POLYLINE? Simply, Polyline is a line connecting three or more points and looks like a single line or curve or both! As we are talking about flutter and
google map, the line that represents the route from one point to another is called a Polyline. Actually Polyline is a collection of connected lines. INSTALL PACKAGES At first we will create
a new Flutter project. Then open the pubspec.yaml file and install the latest versions of the following packages : * GOOGLE MAPS FLUTTER PACKAGE * HTTP PACKAGE _Note : Be careful while
editing pubspec.yaml file as it is very sensitive to indentation._ ...dependencies: flutter: sdk: flutter google_maps_flutter: ^0.5.27+3 http: ^0.12.1... GETTING API KEYS Here we
will be dealing with Google Map API and openrouteservice API. * Enable Google Map SDK and API key following _this instructions__. _This will cover how to set up Maps SDK for for both Android
and iOS devices. * Go to OPENROUTESERVICE , create a free account. After they verify your email, you can go straight to your dev dashboard and generate you API Key using verification mail.
We will use this API key to request our data. > You can go to this link to test your API Key and know more about > services of openrouteservice. GET INTO WORK! First we will Create a
Stateful class ‘MyApp’ , which returns a MaterialApp widget. We will import necessary google_map_flutter.dart file for accessing GoogleMap widget. As the GoogleMap widget takes inputs of
type Map<Marker> and Map<Polyline> and PolyLine class takes List<LatLng> as input.We also need a variable for receiving response data. We’ll declare them as followed.
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;// For holding Co-ordinates as LatLng FINAL
LIST<LATLNG> POLYPOINTS = []; //For holding instance of Polyline FINAL SET<POLYLINE> POLYLINES = {}; // For holding instance of Marker FINAL SET<MARKER> MARKERS = {};
VAR DATA; // Dummy Start and Destination Points double startLat = 23.551904; double startLng = 90.532171; double endLat = 23.560625; double endLng = 90.531813; The “onMapCreated:” argument
of GoogleMap Widget expects a callback. We can provide it by creating the following method of same name : void _ONMAPCREATED(GOOGLEMAPCONTROLLER CONTROLLER) { mapController = controller; }
After setting all the parameters of GoogleMap widget, the build method will be like : @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:
AppBar( title: Text('Polyline Demo'), backgroundColor: Colors._green_[700], ), body: GoogleMap( onMapCreated: _ONMAPCREATED,
initialCameraPosition: CameraPosition( target: const LatLng(23.560625, 90.531813), zoom: 15, ), MARKERS: MARKERS, POLYLINES: POLYLINES, ),
), ); } Now we have to populate the Sets of Marker and Polyline. We will put two markers on our map, one at Starting point and other one at Ending point. We’ll create a method for
that and call that method inside _onMapCreated function. void _onMapCreated(GoogleMapController controller) { mapController = controller; SETMARKERS(); }SETMARKERS() {
markers.add(Marker( markerId: MarkerId("Home"), position: LatLng(startLat, startLng), infoWindow: InfoWindow( title: "Home", snippet: "Home
Sweet Home", ), ), ); markers.add(Marker( markerId: MarkerId("Destination"), position: LatLng(endLat, endLng), infoWindow: InfoWindow( title:
"Masjid", snippet: "5 star rated place", ), )); setState(() {}); } If You Run at this stage, you’ll see this: RECEIVING AND PROCESSING DATA Now we will
fetch data from the openrouteservice API by making a http get request. We’ll create a class called NetworkHelper which have a method getData() to make a request for the data. I’ve done this
on another dart file to reduce complexity. import 'PACKAGE:HTTP/HTTP.DART' AS HTTP; import 'DART:CONVERT'; class NetworkHelper{
NetworkHelper({this.startLng,this.startLat,this.endLng,this.endLat}); final String url ='https://api.openrouteservice.org/v2/directions/'; final String APIKEY =
'<YOUR-API-KEY>'; final String pathParam = 'driving-car';// Change it if you want final double startLng; final double startLat; final double endLng; final
double endLat; Future getData() async{ HTTP.RESPONSE RESPONSE = AWAIT HTTP.GET('$url$pathParam?api_key=$apiKey&start=$startLng,$startLat&end=$endLng,$endLat');
if(response.statusCode == 200) { String data = response.body; RETURN JSONDECODE(DATA); } else{ print(response.statusCode); } } } When the class is constructed,
the values for startLng, startLat, endLng, endLat gets initialized . After calling getData() method, it makes a get request using the URL, receives response and returns a dynamic type data
using JSONDECODE() method.If you are not familiar with manual approach of processing JSON data using DART:CONVERT LIBRARY, then check this cookbook. The URL is like this: >
https://api.openrouteservice.org/v2/directions/{PATH-PARAMETER}?api_key={YOUR > API KEY}&start={STARTING LONGITUDE, STARTING LATITUDE}&end={ENDING > LONGITUDE, ENDING LATITUDE}
You can set path-parameter to any of these : * driving-car * driving-hgv * cycling-road * cycling-mountain * cycling-electric * foot-walking * foot-hiking * wheelchair Now we have to use
the class and make our request. So we created another method called getJsonData(). Here we’ll create an object of NetworkHelper class by passing start and end point coordinates. And then
we’ll call the getData() method and receive the returned data. If we take a look at the response of the API, we see it’s a JSON or more accurately a “geoJson” type response. As we only need
the coordinates of the route, we will get them from [“FEATURES”][“GEOMETRY”][“COORDINATES”]. At this position there is a List of Longitude-Latitude pairs. To access this data let’s create a
class LineString which have a List<dynamic> as attribute. class LineString { LineString(this.lineString); LIST<DYNAMIC> LINESTRING; } Now we can load the List of pairs into
an instance of LineString class and using that we can populate the List<LatLng> type variable as followed: void GETJSONDATA() async { // Create an instance of Class NetworkHelper
which uses http package // for requesting data to the server and receiving response as JSON format NetworkHelper NETWORK = NetworkHelper( startLat: startLat, startLng: startLng,
endLat: endLat, endLng: endLng, ); try { // getData() returns a json Decoded data DATA = AWAIT NETWORK.GETDATA(); // We can reach to our desired JSON data manually as
following LINESTRING LS = LINESTRING( DATA['FEATURES'][0]['GEOMETRY']['COORDINATES']); for (int i = 0; i < ls.lineString.length; i++) {
POLYPOINTS.ADD(LATLNG(LS.LINESTRING[I][1], LS.LINESTRING[I][0])); } } catch(e){ print(e); } } We’ll call the function at INITSTATE(). @override void initState() {
super.initState(); GETJSONDATA(); } CREATING POLYLINE At last we can populate our Set of Polylines with the LIST<LATLNG> , which is populated with the coordinates of the route.Then a
SETSTATE((){}) is called to draw the route on the map. setPolyLines() { Polyline polyline = Polyline( polylineId: PolylineId("polyline"), color: Colors._lightBlue_,
points: polyPoints, ); polyLines.add(polyline); setState(() {}); } We’ll call this method after the List<LatLng> is done populating inside the method ‘getJsonData()’ . void
getJsonData() async { ... try { ... Code unchanged... for(...) { ....code unchanged .... } SETPOLYLINES(); } catch(e){ print(e); } } That’s
it!!! Run you code and you can see your route drawn in the map screen. Let me know on comment if you have any query regarding this process. Here is the Github repository for the whole demo
project! Happy Fluttering !!!