'PolylinePoints is not displaying on second search of location in Flutter

I'm trying to calculate the distance between 2 places. Scenario is the source (pickup) place can be different but the destination (drop off) place should be same. At first when i run the app and type the pickup place on textfield and when click on button it shows the PolylinePoints line,marker and i can move the map easily, but when i write other place it points on map, marker is displaying but not showing PolylinePoints line and can't move the map easily.

here is the method to calculate the distance:


Future<bool> _calculateDistance() async {
    try {
      final Uint8List startMarkerIcon =
          await getBytesFromAsset(AssetsPath.startMarkerIcon, 40);
      final Uint8List destinationMarkerIcon =
          await getBytesFromAsset(AssetsPath.markerIcon, 50);

      // Retrieving placemarks from addresses
      List<Location> startPlacemark = await locationFromAddress(_startAddress);
      List<Location> destinationPlacemark =
          await locationFromAddress(_destinationAddress);

      // Use the retrieved coordinates of the current position,
      // instead of the address if the start position is user's
      // current position, as it results in better accuracy.
      double startLatitude = _startAddress == _currentAddress
          ? _currentPosition.latitude
          : startPlacemark[0].latitude;

      double startLongitude = _startAddress == _currentAddress
          ? _currentPosition.longitude
          : startPlacemark[0].longitude;

      double destinationLatitude = destinationPlacemark[0].latitude;
      double destinationLongitude = destinationPlacemark[0].longitude;

      String startCoordinatesString = '($startLatitude, $startLongitude)';
      String destinationCoordinatesString =
          '($destinationLatitude, $destinationLongitude)';

      // Start Location Marker
      Marker startMarker = Marker(
        markerId: MarkerId(startCoordinatesString),
        position: LatLng(startLatitude, startLongitude),
        infoWindow: InfoWindow(
          title: 'Start $startCoordinatesString',
          snippet: _startAddress,
        ),
        icon: BitmapDescriptor.fromBytes(startMarkerIcon),
      );

      
      // Destination Location Marker
      print("destination address    "+_destinationAddress);
      Marker destinationMarker = Marker(
        markerId: MarkerId(destinationCoordinatesString),
        position: LatLng(destinationLatitude, destinationLongitude),
        infoWindow: InfoWindow(
          title: 'Destination $destinationCoordinatesString',
          snippet: _destinationAddress,
        ),
        icon: BitmapDescriptor.fromBytes(destinationMarkerIcon),
      );

      // Adding the markers to the list
      markers.add(startMarker);
      markers.add(destinationMarker);


      // Calculating to check that the position relative
      // to the frame, and pan & zoom the camera accordingly.
      double miny = (startLatitude <= destinationLatitude)
          ? startLatitude
          : destinationLatitude;
      double minx = (startLongitude <= destinationLongitude)
          ? startLongitude
          : destinationLongitude;
      double maxy = (startLatitude <= destinationLatitude)
          ? destinationLatitude
          : startLatitude;
      double maxx = (startLongitude <= destinationLongitude)
          ? destinationLongitude
          : startLongitude;

      double southWestLatitude = miny;
      double southWestLongitude = minx;

      double northEastLatitude = maxy;
      double northEastLongitude = maxx;

      // Accommodate the two locations within the
      // camera view of the map
      mapController.animateCamera(
        CameraUpdate.newLatLngBounds(
          LatLngBounds(
            northeast: LatLng(northEastLatitude, northEastLongitude),
            southwest: LatLng(southWestLatitude, southWestLongitude),
          ),
          100.0,
        ),
      );
      await _createPolylines(startLatitude, startLongitude, destinationLatitude,
          destinationLongitude);

      double totalDistance = 0.0;

      // Calculating the total distance by adding the distance
      // between small segments
      for (int i = 0; i < polylineCoordinates.length - 1; i++) {
        setState(() {
          totalDistance += _coordinateDistance(
            polylineCoordinates[i].latitude,
            polylineCoordinates[i].longitude,
            polylineCoordinates[i + 1].latitude,
            polylineCoordinates[i + 1].longitude,
          );
        });
      }

      setState(() {
        _placeDistance = totalDistance.toStringAsFixed(2);
        print('DISTANCE: $_placeDistance km');
      });

      return true;
    } catch (e) {
      print(e);
    }
    return false;
  }


Formula for calculating distance between two coordinates

  double _coordinateDistance(lat1, lon1, lat2, lon2) {
    var p = 0.017453292519943295;
    var c = cos;
    var a = 0.5 -
        c((lat2 - lat1) * p) / 2 +
        c(lat1 * p) * c(lat2 * p) * (1 - c((lon2 - lon1) * p)) / 2;
    return 12742 * asin(sqrt(a));
  }

Create the polylines for showing the route between two places

  _createPolylines(
    double startLatitude,
    double startLongitude,
    double destinationLatitude,
    double destinationLongitude,
  ) async {
    polylinePoints = PolylinePoints();
    PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
      "key here", // Google Maps API Key
      PointLatLng(startLatitude, startLongitude),
      PointLatLng(destinationLatitude, destinationLongitude),
      travelMode: TravelMode.transit,
    );

    if (result.points.isNotEmpty) {
      result.points.forEach((PointLatLng point) {
        polylineCoordinates.add(LatLng(point.latitude, point.longitude));
      });
    }

    PolylineId id = PolylineId('poly');
    Polyline polyline = Polyline(
      visible: true,
      patterns: [
                PatternItem.dash(8),
                PatternItem.gap(10),
              ],
      polylineId: id,
      color: Colors.orange,
      points: polylineCoordinates,
      width: 3,
    );
    polylines[id] = polyline;
  }


here is the google map code

  SizedBox(
                    height: 0.57.sh,
                    width: 1.0.sw,
                    child: GoogleMap(
                      markers: Set<Marker>.from(markers),
                      initialCameraPosition: _initialLocation,
                      myLocationEnabled: true,
                      myLocationButtonEnabled: true,
                      compassEnabled: true,
                      mapType: MapType.normal,
                      
                      // zoomGesturesEnabled: true,
                      zoomControlsEnabled: true,
                      polylines: Set<Polyline>.of(polylines.values),
                      onMapCreated: (GoogleMapController controller) {
                        mapController = controller;
                      },
                    ),
                  ),

button click code

                 SizedBox(
                      width: 0.8.sw,
                   height: 0.08.sh,
                    child: ElevatedButton(
                      onPressed: 
                           () async {
                              setState(() {
                                if (markers.isNotEmpty) markers.clear();
                                if (polylines.isNotEmpty) {
                                  polylines.clear();
                                }
                                if (polylineCoordinates.isNotEmpty) {
                                  polylineCoordinates.clear();
                                }
                                _placeDistance = null;
                              });
                  
                              _calculateDistance().then((isCalculated) {
                                if (isCalculated) {
                                  print("RETURNED VALUE IS " +
                                      isCalculated.toString());
                                  // ScaffoldMessenger.of(context).showSnackBar(
                                  //   const SnackBar(
                                  //     content:
                                  //         Text('Distance Calculated Sucessfully'),
                                  //   ),
                                  // );
                                } else {
                                  // ScaffoldMessenger.of(context).showSnackBar(
                                  //   const SnackBar(
                                  //     content: Text('Error Calculating Distance'),
                                  //   ),
                                  // );
                                }
                              });
                            },
                        
                      child: Center(
          child:  Text("Find Ride",style: TextStyle(color: Colors.white,fontSize: 20.0.sp,fontFamily: Apptheme.redHatMedium,
                      ),
          ),
                      ),
                     
                      ),
                    ),
                  ),

please help how can fix this issue. Many thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source