【问题标题】:flutter batch http requests颤振批处理http请求
【发布时间】:2020-11-09 04:20:09
【问题描述】:

我正在尝试向 google maps api 发送多个 http 请求,以获取旅程所需的时间。使用以下代码:

 getRouteCoordinates(LatLng sourceCords, LatLng destCords)async{
  String url = "https://maps.googleapis.com/maps/api/directions/json?origin=${sourceCords.latitude},${sourceCords.longitude}&destination=${destCords.latitude},${destCords.longitude}&key=$apiKey";
  http.Response response = await http.get(url);
  Map values = jsonDecode(response.body);
 
}

所以我决定使用这个包 [batching_future],但我似乎无法理解如何使用这个包来使其工作。

我想用目标输入来做这个批处理请求,比如

  var inputs = [
    LatLng(43.721160, 45.394435),
    LatLng(23.732322, 78.385142),
    LatLng(21.721160, 90.394435),
    LatLng(13.732322, 59.385142),
    LatLng(47.721160, 80.394435),
    LatLng(25.732322, 60.385142),
  ];

我怎样才能做到这一点。提前致谢。

【问题讨论】:

  • inputs 如何映射到每个getRouteCoordinates 调用?

标签: google-maps flutter dart


【解决方案1】:

gmaps_multidestination 包负责跟踪。

在下面复制并粘贴运行批处理请求的相关代码:

import 'package:google_maps_webservice/distance.dart';
import 'package:meta/meta.dart';

/// Computes travel times from [myLocation] to [destinations] in batch using
/// Google Distance Matrix API and [apiKey].
///
/// Requires Google Maps API Key, Google Distance Matrix API, and is subject
/// to the limitations of the Matrix API (such as maximum destinations per
/// request)
Future<Map<Location, Duration>> batchTravelTimes(
        {@required Location myLocation,
        @required List<Location> destinations,
        @required String apiKey}) async =>
    (await GoogleDistanceMatrix(apiKey: apiKey)
            .distanceWithLocation([myLocation], destinations))
        .results
        .expand((row) => row.elements)
        .toList()
        .asMap()
        .map((i, location) => MapEntry(
            destinations[i], Duration(seconds: location.duration.value)));

连接上面batching_future的代码是:

/// Computes travel times from `O` to `[D1,D2,D3]` in batch.
/// Requires Google Maps API Key, Google Distance Matrix API, and is subject
/// to the limitations of the Matrix API (such as maximum destinations per
/// request)
import 'package:batching_future/batching_future.dart';
import 'package:google_maps_webservice/distance.dart';
import 'package:meta/meta.dart';

typedef MyLocationProvider = Future<Location> Function();

BatchingFutureProvider<Location, Duration> batchingFutureTravelTime(
        {@required MyLocationProvider myLocationProvider,
        @required String apiKey}) =>
    createBatcher(
      (destinations) async => (await batchTravelTimes(
              apiKey: apiKey,
              myLocation: await myLocationProvider(),
              destinations: destinations))
          .values
          .toList(),
      maxBatchSize: 20,
      maxWaitDuration: Duration(milliseconds: 200),
    );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 2020-09-30
    • 2021-05-05
    • 2021-07-04
    • 1970-01-01
    • 2021-02-23
    • 2020-06-18
    相关资源
    最近更新 更多