Rafael Canuto
Rafael Canuto

Reputation: 95

How can I draw a route between two geopoints on the Flutter?

How can I draw a route between two geopoints on the Flutter with the new widget Google Maps? There were some tutorials about how to do this with the previous widget, but now it's deprecated.

Upvotes: 2

Views: 5636

Answers (1)

Gratien Asimbahwe
Gratien Asimbahwe

Reputation: 1614

There are many ways of implementing it. This is how I did it few weeks ago. First i had these plugins:

import 'package:flutter_google_places/flutter_google_places.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

next create your GoogleMap object:

LatLng izp = LatLng(-3.386943, 29.371636);

  GoogleMap googleMap = GoogleMap(
      initialCameraPosition: CameraPosition(target: izp, zoom: 10.0),
      compassEnabled: true,
      scrollGesturesEnabled: true,
      zoomGesturesEnabled: true,
      onMapCreated: (g) {
        gmc = g;//for mapcontroller if any
      },
      markers: {},
      polylines: {},//initialize the polylines list
    );

From Google Directions, fetch directions between your two points. Decode the result and get points. should be at this position:

dynamic directions = decodedResult["routes"][0]["overview_polyline"]['points'];

Create a PolylinePoints object and decode your directions object:

PolylinePoints points = new PolylinePoints();

List<PointLatLng> result = points.decodePolyline(directions);

Create a list of LatLng from the list of PointLatLng:

List<LatLng> po = [];
      result.forEach((f) {
        po.add(LatLng(f.latitude, f.longitude));
      });

Then with that list of LatLng, create a polyline object:

 Polyline route = new Polyline(
          polylineId: PolylineId("route"),
          geodesic: true,
          points: po,
          width: 20,
          color: Colors.blue);

Then after set the polyline object to the your google map object:

 setState(() {
 //if you created markers, add them too if you wish
        googleMap.markers.add(marker);
        googleMap.markers.add(marker2);
        googleMap.polylines.add(route);

        /*if you associated a googlemapcontroller, you can do further actions like zooming...*/
      });

I think this should help. Good luck

Upvotes: 3

Related Questions