Search code examples
firebasefluttergoogle-mapsgeolocationfluttermap

Flutter : polylines show straight line


Im implementing a flutter app to display polylines by flutter google maps plugin, But It only shows a straight line between those two points rather than showing actual route, I'm not quite sure what needed to do.

Here my add markers function

void addMarker() {
latlng.add(LatLng(5.973804, 80.429838));
allMarkers.add(Marker(
  markerId: MarkerId('busLoc'),
  draggable: true,
  onTap: () {
    print('Marker Tapped');
  },
  position: LatLng(5.973804, 80.429838),
));

_polyline.add(Polyline(
  color: Colors.blue,
  visible: true,
  points: latlng,
  polylineId: PolylineId("distance"),
));

Here my scaffold

GoogleMap(
    
    polylines: _polyline,
    markers: Set.from(allMarkers),
    initialCameraPosition:
        CameraPosition(target: LatLng(widget.la, widget.l0), zoom: 14),
    mapType: MapType.normal,
  ),

And I'll attach screenshot below as wellenter image description here


Solution

  • To get the route from point A to point B you will need to use Directions API that is available on the google_maps_webservice flutter package, which is a service from Google Maps Platform that gives the route information

    One of the route information is the overview_polyline that holds an encoded polyline representation of the route.

    You can get the overview_polyline by having a function that sends request to Directions API using the google_maps_webservice package like this:

    import 'package:google_maps_webservice/directions.dart' as directions;
    
    final _directions = new directions.GoogleMapsDirections(apiKey: "YOUR_API_KEY");
    
    var overviewPolylines;
    
    directions.DirectionsResponse dResponse = await _directions.directionsWithAddress(
         _originAddress, 
         _destinationAddress, 
    );
    
    if (dResponse.isOkay) {
      for (var r in dResponse.routes) {
        overviewPolylines = r.overviewPolyline.points
      }
    }
    

    Then, once you get the overview_polyline from Directions API using the sample code above, you will need to decode it using the PolyUtil(); method from the google_maps_util flutter package like this:

    import 'package:google_maps_util/google_maps_util.dart';
    
    PolyUtil myPoints = PolyUtil();
    var pointArray = myPoints.decode(overviewPolylines);
    

    Once decoded you can pass the pointArray to your polyline object like this:

    _polyline.add(Polyline(
     color: Colors.blue,
      visible: true,
      points: pointArray,
      polylineId: PolylineId("distance"),
    ));