Google API |距离矩阵

时间:2020-10-08 12:35:20

标签: google-api google-distancematrix-api

我的代码需要帮助。

首先,我的方法是否正确,我使用GoogleDistanceMatrix来获取真实的路线距离,而不仅仅是线性距离?

我想使用地理坐标作为起点和终点地址,但它似乎不起作用:

public double CalculateGoogleDistance(GeoCoordinate from, GeoCoordinate to) {
  DistanceMatrixRequest request = new DistanceMatrixRequest();
  request.Key = "****";

  request.Origins = new Location[] {
    new Location(from)
  };
  request.Destinations = new Location[] {
    new Location(to)
  };

  var response = GoogleApi.GoogleMaps.DistanceMatrix.Query(request);

  return response.Rows.First().Elements.First().Distance.Value;
}

1 个答案:

答案 0 :(得分:1)

首先,您在使用Google Maps API服务时似乎正在使用第三方库/存储库,因此我建议您仅遵循它们的正式文档,在回答您的问题时将提供这些文档。

如他们的official documentation中所述,即使它是可选的,默认的trafic_model还是bestguess,这意味着结果将基于对行进时间的最佳估计。了解历史路况和实时路况。您可以了解有关其他流量模型可选参数here的更多信息。

现在,关于获得“真实路线距离”,您仅指的是实时结果,不包括历史流量。为此,您需要按照文档中的示例所示,指定departureTime到现在:

drivingOptions: {
    departureTime: new Date(Date.now() + N),  // for the time N milliseconds from now.
    trafficModel: 'bestguess'
}

如您所见,距离矩阵API就是这样工作的。

注意:出发时间和交通模型也适用于Directions API。

有关Distance Matrix API Web服务的Web服务版本,请参见此链接。