adding polyline "sub destinations" google maps flutter, optimize for a single API call

Issue

The application that I’m trying to create required the creation of a route that has destinations between the starting and ending point, between the beginning and end provided in the getRouteBetweenCoordinates, I need a way to add a custom Latlong pair that must travel through, instead of finding the quickest route, I need it to route between all points that I provided while still following the road (not just a direct line).

The only method that I could come up with is recalling the setPolyLines function for each stretch that makes up the total route. While this method could get the desired result, it required making multiple API calls, ideally, the entirety of the custom route would be loaded upon that first directions API call.

Here is the code that I’m working with, Is there an easier solution to this problem that I missed? This may be very obvious but I’m new with google maps integration so sorry if that’s the case.

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
//new polyline between each destination

class Tour extends StatefulWidget {
  const Tour({Key? key}) : super(key: key);

  @override
  _TourState createState() => _TourState();
}

class _TourState extends State<Tour> {
  late GoogleMapController mapController;

  //poly line variables
  Set<Polyline> _polyLine = Set<Polyline>();

  List<LatLng> polylineCordinates = [];
  late PolylinePoints polylinePoints;

  //starting location
  static const _start =
      CameraPosition(target: LatLng(48.696985, -122.905595), zoom: 17.0);

  //METHODS
  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
    //TODO: provide with start and end point for specific line, end of last ==
    //start of next
    setPolyLines(PointLatLng(48.696985, -122.905595),
        PointLatLng(48.657421, -122.917412));
    setPolyLines(PointLatLng(48.657421, -122.917412),
        PointLatLng(48.644983, -122.944760));
  }

  void setPolyLines(PointLatLng start, PointLatLng end) async {
    //polyline result DT is a collection of latlng following roads
    PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
        "MY API KEY IS HERE",
        //route start
        start,
        //route end
        end);
    //list of latlng pairs in order of exectecution
    //this is preparing the drawing of the line, the set state plots it out
    if (result.status == 'OK') {
      result.points.forEach((PointLatLng point) {
        polylineCordinates.add(LatLng(point.latitude, point.longitude));
      });
    }

    setState(() {
      _polyLine.add(Polyline(
          width: 10,
          //set id to
          polylineId: PolylineId("route"),
          color: Color(0xFF00BFA6),
          points: polylineCordinates));
    });
  }

  @override
  void initState() {
    polylinePoints = PolylinePoints();
  }

  @override
  void dispose() {
    mapController.dispose();
    super.dispose();
  }

  //upon call, modal sheet toggles from the bottom of screen
  modalSheet() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return Column(
            children: [
              Container(
                height: 200,
                color: Colors.amber,
              ),
              Container(
                height: 100,
                color: Colors.blue,
              )
            ],
          );
        });
  }

  //adjusts camera position to the _start location
  center() {
    mapController.animateCamera(CameraUpdate.newCameraPosition(_start));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GoogleMap(
          polylines: _polyLine,
          myLocationButtonEnabled: false,
          zoomControlsEnabled: false,
          onMapCreated: _onMapCreated,
          initialCameraPosition: _start),
      floatingActionButton: FloatingActionButton(
          onPressed: () => center(), child: Icon(Icons.add)),
    );
  }
}

Solution

You can use wayPoints parameter of getRouteBetweenCoordinates method which accepts a list of PolylineWayPoint (List<PolylineWayPoint>).

PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
        googleAPiKey,
        PointLatLng(48.696985, -122.905595),
        PointLatLng(48.644983, -122.944760),
        wayPoints: [PolylineWayPoint(location: "48.657421,-122.917412")]);

Please see the image below for the result using your sample code.enter image description here

Answered By – Nelson Jr.

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.