-2

In Flutter I use google_maps_flutter, google_directions_api and flutter_polyline_points packages to have a map with the following functionalities;

Drawing routes between current location and destination points, get distance and durations between them, driver must be notified to take left/right while driving to the destination.

I have done these all, but when current location keeps updating on the map I'm calling direction api which return lots of data like legs and steps this api call is almost every second and google will charge me a lot.

Is anybody faced to same issue, I really appreciate a help.

There is part of my codes I have done so far

  void _getCurrentLocation(context) {
    showGeneralDialog(
        context: context,
        barrierDismissible: false,
        barrierColor: Colors.black45,
        pageBuilder: (BuildContext buildContext, Animation animation,
            Animation secondaryAnimation) {
          return Center(
            child: Container(
              width: MediaQuery.of(context).size.width - 10,
              height: MediaQuery.of(context).size.height - 80,
              padding: EdgeInsets.all(20),
              color: Tingsapp.transparent,
              child: CurrentLocation(),
            ),
          );
        }).then((location) {
      if (location != null) {
        _addMoverMarker(location, 'mover');
        //updateFirebase(location);
        _animateCameraToCurrentLocation(location);
      }
    });
  }

destination point are already set. In the above code I get user current location and add a marker as bellow

  void _addMoverMarker(newLocationData, String id) async {
    Uint8List imageData = await getMarker();
    //LatLng latlng = LatLng(newLocationData.latitude, newLocationData.longitude);
    LatLng latlng = LatLng(_moverLatitude!, _moverLongitude!);
    MarkerId markerId = MarkerId(id);
    Marker marker = Marker(
      markerId: markerId,
      position: latlng,
      zIndex: 2,
      icon: BitmapDescriptor.fromBytes(imageData),
      infoWindow: InfoWindow(
        title: "Mover location",
      ),
    );
    markers[markerId] = marker;
    circle = Circle(
      circleId: CircleId("circle"),
      radius: 20,
      zIndex: 1,
      center: latlng,
      strokeColor: Colors.orange.withAlpha(60),
      fillColor: Colors.orange.withAlpha(300),
    );
    _getMoverPolyline(newLocationData);
  }

and here I animate the camera

  _animateCameraToCurrentLocation(newLocationData) {
    if (_locationSubscription != null) {
      _locationSubscription!.cancel();
    }
    _locationSubscription =
        _locationTracker.onLocationChanged.listen((newLocationData) {
      if (_mapController != null) {
        _addMoverMarker(newLocationData, 'mover');
        _animateCamera(_moverLatitude, _moverLongitude, 16.0);
        //updateFirebase(newLocationData);
      }
    });
  }

when I draw the polyline I call directions api here my problem starts

_getMoverPolyline(LocationData locationData) async {
    PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
      mapKey,
      PointLatLng(_originLatitude!, _originLongitude!),
      PointLatLng(_moverLatitude!, _moverLongitude!),
      //PointLatLng(locationData.latitude!, locationData.longitude!),
      travelMode: TravelMode.driving,
    );

    if (result.points.isNotEmpty) {
      moverPolylineCoordinates = [];
      result.points.forEach((PointLatLng point) {
        moverPolylineCoordinates.add(LatLng(point.latitude, point.longitude));
      });
    }
    _addMoverPolyLine();
    _getDirections(_moverLatitude, _moverLongitude, _originLatitude,
        _originLongitude).then((data){
         _updateData(data);
    });
  }


  _getDirections(_moverLatitude, _moverLongitude, _originLatitude, _originLongitude) async {
    Api api = Api();
    var res = await api.getDirections(
        _moverLatitude, _moverLongitude, _originLatitude, _originLongitude);
    var jsonData = jsonDecode(res.body);
    print(jsonData['routes'][0]['legs'][0]);
    return jsonData['routes'][0]['legs'][0];
  }

In the above code _getDirections method gets calling every second.

Isn't possible to call directions api one time?

_updateData method update data like tern right/left or Head south on my map

Zia
  • 506
  • 3
  • 20

2 Answers2

0

No I don't think that it's good practice to keep calling the API. And even in the google_directions_api documentation, they say,

Note: This service is not designed to respond in real time to user input.

And to answer your main question.. Don't call the API every time the location changes, instead call it once using the current location. And the response contains everything you need to navigate the user. Check the maneuver key inside each step of a leg.

And you should only use the location subscription to update the current location and animate the camera on the map. Use the getLocation() method to get the current location before starting the trip and use that location to generate the route. Store that route in a variable and use the data inside the route response to display whatever you want.

-1

It´s not a good practice to constantly call directionsAPI, for the good of your pocket and to follow the recommendations of google.

If you are creating a Navigation app you first need to call the Api when the user set a destination, capture de coordinates (overview_polyline) and after that if the user goes off the road you can use maps toolkit to determine when this occurs and after that call again directionsAPI.

lasd
  • 26
  • 4