How to display travel time in google maps in flutter?

1,721

You can use the Distance Matrix API after you enable it.

https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=lat,lng&destinations=lat,lng&key=API-Key

Share:
1,721
mary kor
Author by

mary kor

Updated on November 21, 2022

Comments

  • mary kor
    mary kor over 1 year

    I would like to get the travel time displayed from the JSON data for the current location of the user. At the moment, I only have polylines displayed from the current location to the destination. My code:

    import 'package:http/http.dart' as http;
    import 'dart:convert';
    import 'dart:async';
    
    const apiKey = "xxxxxxx";
    
      class GoogleMapsServices {
      Future<String> getRouteCoordinates(LatLng l1, LatLng l2) async {
      String url = "https://maps.googleapis.com/maps/api/directions/json?origin=${l1
          .latitude},${l1.longitude}&destination=${l2.latitude},${l2
          .longitude}&mode=walking&key=$apiKey";
      http.Response response = await http.get(url);
      Map values = jsonDecode(response.body);
      print("====================>>>>>>>>${values}");
    
      return values["routes"]["distance"]["duration"]["overview_polyline"]["points"];
    
      }
      }```
    
     List<LatLng> _convertToLatLng(List points) {
        List<LatLng> result = <LatLng>[];
        for (int i = 0; i < points.length; i++) {
          if (i % 2 != 0) {
            result.add(LatLng(points[i - 1], points[i]));
          }
        }
    void createRoute(String encondedPoly) {
        _polyLines.add(Polyline(
            polylineId: PolylineId(latLng.toString()),
            width: 4,
            points: _convertToLatLng(_decodePoly(encondedPoly)),
            color: Colors.deepOrange),
        );
      }
    
    List _decodePoly(String poly) {
        var list = poly.codeUnits;
        var lList = new List();
        int index = 0;
        int len = poly.length;
        int c = 0;
        do {
          var shift = 0;
          int result = 0;
    
          do {
            c = list[index] - 63;
            result |= (c & 0x1F) << (shift * 5);
            index++;
            shift++;
          } while (c >= 32);
          if (result & 1 == 1) {
            result = ~result;
          }
          var result1 = (result >> 1) * 0.00001;
          lList.add(result1);
        } while (index < len);
    
        for (var i = 2; i < lList.length; i++)
          lList[i] += lList[i - 2];
    
        print(lList.toString());
    
        return lList;
      }
    Widget _mapWidget() {
        return GoogleMap(
          mapType: MapType.hybrid,
          polylines: polyLines,
          markers: _createMarker(),
          initialCameraPosition: CameraPosition(
              target: latLng, zoom: 12.0),
          onMapCreated: (GoogleMapController controller) {
            _controller = controller;
            _setMapPins();
          },
          onCameraMove: onCameraMove,
          tiltGesturesEnabled: false,
          onTap: (LatLng location) {
            setState(() {
              _pinPillPosition = -100;
    
              _pinPillPosition2 = -100;
              _polyLines.clear();
            });
          },
        );
      }
        return result;
      }
    void sendRequest() async {
        LatLng destination = LatLng(52.523778, 13.405193);
        String route = await _googleMapsServices.getRouteCoordinates(
            latLng, destination);
        createRoute(route);
      }
    
    
    

    I would like to have the time and distance displayed in a pill container that pop-ups when a marker is clicked. Thank you in advance.

  • Zia
    Zia about 2 years
    How to show distance and duration on the map over drawn line between A and B. I can get the distance and duration from distanceMetrix api. my problem is showing on the line.
  • Emmanuel Afolabi
    Emmanuel Afolabi about 2 years
    oh, what I can think tho is for you to paint on the drawn line from your gotten data.