Home > Back-end >  Google Maps Polyline not Appearing
Google Maps Polyline not Appearing

Time:03-18

I am trying to have several polylines appear in my GoogleMaps widget of my Flutter Dart Android app, yet they do not appear. The widget and map appear perfectly, but the Polylines are absent.

When my code runs, a polyline is successfully added to _polylines, and the GoogleMaps widget contains "polylines: _polylines", they they still wont show up.

Any thoughts?

My code appears as below:

class TotalStatsViewModel extends BaseViewModel {
  final _navigationService = locator<NavigationService>();
  Set<Polyline> _polylines = HashSet<Polyline>();
  GoogleMapController mapController;

  Widget getWidget() {
    if (getLoggedInUser().activityList.length != 0) {
      return Column(
        children: [
          getMap(),
          Text(
            'Total Distance Biked:',
            textScaleFactor: 2,
          ),
          Text(
            getTotalDistance(),
            textScaleFactor: 1.5,
          ),
          Text(
            'Total Duration Biked:',
            textScaleFactor: 2,
          ),
          Text(
            getTotalDuration(),
            textScaleFactor: 1.5,
          ),
          Text(
            'Average Biking Speed:',
            textScaleFactor: 2,
          ),
          Text(
            getAverageSpeed(),
            textScaleFactor: 1.5,
          ),
          Spacer(),
          Padding(
              padding: const EdgeInsets.all(10.0),
              child: ElevatedButton(
                onPressed: () {
                  routeToHubView();
                },
                child: Text('Return'),
              )),
          Row(), //Row is here to center the column by adding a max width element.
        ],
      );
    } else {
      return Column(
        children: [
          Text(
            'User needs at least one added activity to display statistics.',
            textScaleFactor: 1.5,
            textAlign: TextAlign.center,
          ),
          Spacer(),
          Padding(
              padding: const EdgeInsets.all(10.0),
              child: ElevatedButton(
                onPressed: () {
                  routeToHubView();
                },
                child: Text('Return'),
              )),
          Row(), //Row is here to center the column by adding a max width element.
        ],
      );
    }
  }

  Widget getMap() {
    for (int i = 0; i < getLoggedInUser().activityList.length; i  ) {
      constructPolyline(getLoggedInUser().activityList[i]);
    }
    return SizedBox(
      height: 300,
      child: GoogleMap(
        mapType: MapType.normal,
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          //target: LatLng(45.521563, -122.677433),
          target: LatLng(47.6645740, -122.0411640),
          zoom: 11.0,
        ),
        polylines: _polylines,
      ),
    );
  }

  void constructPolyline(Activity activity) {
    print('CONSTRUCT POLYLINE CALLED');
    List<LatLng> polylineLatLongs = [];
    //fix with activity
    Gpx gpx = GpxReader().fromString('<?xml version="1.0" encoding="UTF-8"?>'
        '<gpx creator="StravaGPX" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd" version="1.1" xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3">'
        '<metadata>'
        '<time>2022-02-06T21:22:54Z</time>'
        '</metadata>'
        '<trk>'
        '<name>Afternoon Ride</name>'
        '<type>1</type>'
        '<trkseg>'
        '<trkpt lat="47.6645740" lon="-122.0411640">'
        '<ele>113.0</ele>'
        '<time>2022-02-06T21:22:54Z</time>'
        '<extensions>'
        '<power>0</power>'
        '<gpxtpx:TrackPointExtension>'
        '<gpxtpx:atemp>22</gpxtpx:atemp>'
        '<gpxtpx:hr>85</gpxtpx:hr>'
        '<gpxtpx:cad>37</gpxtpx:cad>'
        '</gpxtpx:TrackPointExtension>'
        '</extensions>'
        '</trkpt>'
        '<trkpt lat="47.6645750" lon="-122.0411670">'
        '<ele>128.0</ele>'
        '<time>2022-02-06T21:22:55Z</time>'
        '<extensions>'
        '<power>0</power>'
        '<gpxtpx:TrackPointExtension>'
        '<gpxtpx:atemp>22</gpxtpx:atemp>'
        '<gpxtpx:hr>87</gpxtpx:hr>'
        '<gpxtpx:cad>37</gpxtpx:cad>'
        '</gpxtpx:TrackPointExtension>'
        '</extensions>'
        '</trkpt>');
    //debug code
    print('trks: '   gpx.trks.length.toString());
    print('trksegs: '   gpx.trks[0].trksegs.length.toString());
    print('trkpts: '   gpx.trks[0].trksegs[0].trkpts.length.toString());

    for (int i = 0; i < gpx.trks.length; i  ) {
      for (int j = 0; j < gpx.trks[i].trksegs.length; j  ) {
        for (int k = 0; k < gpx.trks[i].trksegs[j].trkpts.length; k  ) {
          polylineLatLongs.add(LatLng(gpx.trks[i].trksegs[j].trkpts[k].lat,
              gpx.trks[i].trksegs[j].trkpts[k].lon));
          print('ITERATION DONE');
        }
      }
    }
    print(polylineLatLongs.toString());
    //polylineLatLongs.add(LatLng(47.664574, -122.041164));
    //polylineLatLongs.add(LatLng(47.664575, -122.041167));

    _polylines.add(Polyline(
        polylineId: PolylineId('0'),
        points: polylineLatLongs,
        color: Colors.red,
        visible: true,
        width: 10));
    print(_polylines.toString());
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  String getTotalDistance() {
    User user = getLoggedInUser();
    double distanceSum = 0;
    for (int i = 0; i < user.activityList.length; i  ) {
      distanceSum  = user.activityList[i].distance;
    }
    distanceSum = double.parse((distanceSum).toStringAsFixed(2));
    return distanceSum.toString()   ' miles';
  }

  String getTotalDuration() {
    User user = getLoggedInUser();
    int totalSeconds = 0;
    for (int i = 0; i < user.activityList.length; i  ) {
      totalSeconds  = user.activityList[i].duration.inSeconds;
    }
    Duration totalDuration = Duration(seconds: totalSeconds);
    List<String> splitDistance = totalDuration.toString().split('.');
    return splitDistance[0];
  }

  String getAverageSpeed() {
    User user = getLoggedInUser();
    double avgSpeed = 0;
    for (int i = 0; i < user.activityList.length; i  ) {
      avgSpeed  = user.activityList[i].avgerageSpeed;
    }
    avgSpeed /= user.activityList.length;
    avgSpeed = double.parse((avgSpeed).toStringAsFixed(2));
    return avgSpeed.toString()   ' miles per hour';
  }

  void routeToHubView() {
    _navigationService.navigateTo(HubViewRoute);
  }
}

CodePudding user response:

Use this code:

Set<Polyline> _directionPolyline = {};

Polyline polyLine = Polyline(
        polylineId: const PolylineId('direction'),
        color: Colors.blue,
        points: List.empty(growable: true),
        width: 5,
        startCap: Cap.roundCap,
        endCap: Cap.roundCap,
        jointType: JointType.round,
        geodesic: true,
      );
    polyLine.points.add(LatLng(element.latitude, element.longitude));
    polyLine.points.add(LatLng(element.latitude, element.longitude));
    _directionPolyline.add(polyLine);

And please rearrange the code... I just give the snippets.

 return SizedBox(
      height: 300,
      child: GoogleMap(
        mapType: MapType.normal,
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          //target: LatLng(45.521563, -122.677433),
          target: LatLng(47.6645740, -122.0411640),
          zoom: 11.0,
        ),
        polylines: _directionPolyline,
      ),
    )
  • Related