【问题标题】:Google maps direction from one start point to multiple end point谷歌地图方向从一个起点到多个终点
【发布时间】:2017-09-18 05:39:56
【问题描述】:

我在地图上有一个起点坐标。我有多个(100)个端点来计算从起点到终点的总距离。 起点是我的办公室,终点是我客户的位置。我想计算总距离。

我在 javascript 上使用 for 循环

for (var i = 0; i < destinations.length; i++) {

    var request = {
        origin: "60.758447, 69.385923",
        destination: destinations[i],
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            var directionsDisplay = new google.maps.DirectionsRenderer();
            directionsDisplay.setMap(map);
            directionsDisplay.setDirections(response);
            totalKM = totalKM + (response.routes[0].legs[0].distance.value / 1000);
            distanceInput.value = totalKM;
            console.log(totalKM)
        }
    });

};

但此循环仅适用于 10 个目的地。我可以在控制台日志中看到这一点。 google有限制查询限制吗?

【问题讨论】:

  • 您是对的,Google 确实限制了您可以快速连续拨打的directionService 数量。 Check here 你能做多少。如果您在 if (status == google.maps.DirectionsStatus.OK) 之外进行检查,我确定状态将是 OVER_QUERY_LIMIT 或类似的。
  • 如果只需要行驶距离,可以试试距离矩阵。
  • 是的,我只需要距离总和。

标签: javascript google-maps


【解决方案1】:

在发布的其中一个 cmets 中,提到了距离矩阵 API。我会推荐这个,因为你只有一个起点和多个目的地。使用方向 API,您只能拥有一对起点和终点,但使用距离矩阵 API,您可以拥有多个终点和起点。距离矩阵 API 还允许每个请求 100 个元素(number_of_elements = number_of_origins * number_of_destinations)。这将允许您在一个请求中拥有一个起点和 100 个目的地。请在此处查看使用限制:

https://developers.google.com/maps/documentation/distance-matrix/usage-limits

当您从 API 获得响应时,您可以通过以下方式获取每个元素的距离:

for(i = 0; i < response.rows[0].elements.length; i++){
    totalDistance += response.rows[0].elements[i].distance.value;
}

它是 rows 数组中的元素 0,因为您只有一个原点,如果您有多个原点,则需要遍历多行。

我还修改了文档中的一个 Google 距离矩阵 API 示例,以总结 3 个目的地与一个起点的距离,只是为了演示它是如何工作的。唯一的区别是在你的应用程序中你会有更多的目的地,但逻辑应该是一样的。请注意,为了安全起见,我从这个小提琴中取出了我的 API 密钥,请输入您自己的以便示例工作:

https://jsfiddle.net/o0wyq4bo/1/

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多