Google Maps JavaScript API V3 - 显示多条路线

sou*_*mer 1 javascript google-maps google-maps-api-3

我正在尝试使用 google 地图 API 显示多条路线。\n但是当尝试超过 10 条路线时,我收到 OVER_QUERY_LIMIT 异常。

\n\n

使用谷歌,我发现,我需要使用回调函数异步调用 DirectionsDisplay (还无法让它工作)。我必须使用某种超时,因为每秒不能发出超过 10 个请求。

\n\n

这是我到目前为止所得到的。

\n\n
<!DOCTYPE html>\n<html>\n<head>\n    <title>Display multiple routes</title>\n    <meta name="viewport" content="initial-scale=1.0">\n    <meta charset="utf-8">\n\n\n    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>\n    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=ENTER_API_KEY"></script>\n\n\n    <style>\n        /* Always set the map height explicitly to define the size of the div\n        * element that contains the map. */\n        #map {\n            height: 100%;\n        }\n        /* Optional: Makes the sample page fill the window. */\n        html, body {\n            height: 100%;\n            margin: 0;\n            padding: 0;\n        }\n    </style>\n\n</head>\n<body>\n\n    <div id="map"></div>\n\n    <script>\n\n        var addresses =\n            [\n                [\'243, Dornacherstrasse\', \'26, Mattenstrasse\'],\n                [\'48 av general de gaulle, saint louis\', \'Gr\xc3\xbcndenstra\xc3\x9fe 40, Muttenz\'],\n                [\'50 ackerstrasse , Basel\', \'holeestrasse 133, Basel\'],\n                [\'71 avenue de B\xc3\xa2le , Saint-Louis \', \'Leonhardstr 6, Basel\'],\n                [\'Ackerstrasse 44, Basel\', \'Petersplatz 1, Basel\'],\n                [\'Ackerstrasse 51, Basel\', \'Maiengasse 51, Basel \'],\n                [\'Aeussere Baselstr. 255, Riehen\', \'zu den drei Linden 80, Basel\'],\n                [\'Aeussere Baselstrasse 309, Riehen\', \'Gotthelfplatz 1, Basel\'],\n                [\'Ahornstrasse 20, Basel\', \'Viaduktstrasse , Basel\'],\n                [\'Albert Schweitzer Strasse 10, Basel\', \'Kohlenberg 17, Basel\'],\n                [\'alemannengasse 17, Basel\', \'Centrahlbahnplatz, Basel\'],\n                [\'Alemannengasse 23, Basel\', \'Peter Merian-Weg 8, Basel\'],\n                [\'Allmendstrasse 233, Basel\', \'Universit\xc3\xa4tsspital Basel, Basel \'],\n                [\'Allmendstrasse 4, Basel\', \'Petersplatz 1, Basel\'],\n                [\'Allschwilerstrasse 106, Basel\', \'Centralbahnstrasse 10 , Basel\'],\n                [\'Allschwilerstrasse 116, Basel\', \'Spitalstrasse 8, Architektur Institut, Basel \'],\n                [\'Allschwilerstrasse 116, Basel\', \'Steinenvorstadt 55, Kino Path\xc3\xa8 K\xc3\xbcchlin, Basel\'],\n                [\'Allschwilerstrasse 48, Basel\', \'Schneidergasse 28, Basel\'],\n                [\'Altrheinweg 52, Basel\', \'Vogesenplatz 1, Basel \'],\n                [\'Am Rheinpark 6, Weil am Rhein\', \'J. J. Balmer-Str. 3, Basel\'],\n                [\'Am Weiher 15, Binningen\', \'Klingelbergstrasse 82, Basel \'],\n                [\'Amerbachstrasse, , Basel\', \'Peter Merian-Weg, Basel\'],\n                [\'Amerikanerstrasse 16, Binningen\', \'Petersplatz 1, Basel\'],\n                [\'Amselweg 20, Reinach\', \'Baselstrasse 33, M\xc3\xbcnchenstein\'],\n                [\'An der Auhalde 15, Riehen\', \'Zu den Dreilinden 95, Basel\'],\n                [\'arnikastr. 22, Riehen\', \'marktplatz, Basel\'],\n                [\'Auf der Lyss 14, Basel\', \'Grenzstrasse 15, Basel\']\n            ];\n\n        var directionsDisplay;\n        var directionsService = new google.maps.DirectionsService();\n        var map;\n\n        function initialize() {\n            directionsDisplay = new google.maps.DirectionsRenderer();\n            var basel = new google.maps.LatLng(41.850033, -87.6500523);\n            var mapOptions = {\n                zoom: 7,\n                center: basel\n            }\n            map = new google.maps.Map(document.getElementById(\'map\'), mapOptions);\n            directionsDisplay.setMap(map);\n        }\n\n        function calcRoute(start, end) {\n\n            var request = {\n                origin: start,\n                destination: end,\n                travelMode: \'BICYCLING\'\n            };\n            directionsService.route(request,\n                function(result, status) {\n                    if (status == \'OK\') {\n\n                        directionsDisplay = new google.maps.DirectionsRenderer({\n                            suppressBicyclingLayer: true,\n                            suppressMarkers: true\n                        });\n                        directionsDisplay.setMap(map);\n                        directionsDisplay.setDirections(result);\n                    }\n                });\n        }\n\n        initialize();\n        addresses.forEach(function (v, i) {\n            setTimeout(calcRoute(addresses[i][0], addresses[i][1]), 100);\n        });\n    </script>\n</body>\n</html>\n
Run Code Online (Sandbox Code Playgroud)\n\n

我知道SO上有很多类似的问题。但他们都不适合我。

\n

geo*_*zip 6

使用 Google Maps API v3 中的相关答案OVER_QUERY_LIMIT 中的修改后的代码:如何在 Javascript 中暂停/延迟以减慢速度?它通过检测 OVER_QUERY_LIMIT 状态并增加发生请求之间的延迟来解决与 Google Maps Javascript API v3 Geocoder 相同的问题。

\n\n
// delay between directions requests\nvar delay = 100;\n\nfunction calcRoute(start, end, next) {\n  console.log("calcRoute(\'" + start + "\',\'" + end + "\',next)");\n  var request = {\n    origin: start,\n    destination: end,\n    travelMode: \'BICYCLING\'\n  };\n  directionsService.route(request,\n    function(result, status) {\n      if (status == \'OK\') {\n\n        directionsDisplay = new google.maps.DirectionsRenderer({\n          suppressBicyclingLayer: true,\n          suppressMarkers: true,\n          preserveViewport: true // don\'t zoom to fit the route\n        });\n        directionsDisplay.setMap(map);\n        directionsDisplay.setDirections(result);\n        // combine the bounds of the responses\n        bounds.union(result.routes[0].bounds);\n        // zoom and center the map to show all the routes\n        map.fitBounds(bounds);\n      }\n      // ====== Decode the error status ======\n      else {\n        console.log("status=" + status + " (start=" + start + ", end=" + end + ")");\n        // === if we were sending the requests to fast, try this one again and increase the delay\n        if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {\n          nextAddress--;\n          delay += 100;\n          document.getElementById(\'delay\').innerHTML = delay;\n        } else {\n          var reason = "Code " + status;\n          var msg = \'start="\' + start + \' end="\' + end + \'"" error=\' + reason + \'(delay=\' + delay + \'ms)<br>\';\n          document.getElementById("messages").innerHTML += msg;\n        }\n      }\n      next();\n    });\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

概念证明小提琴

\n\n

结果地图的屏幕截图

\n\n

代码片段:

\n\n

\r\n
\r\n
// delay between directions requests\nvar delay = 100;\n\nfunction calcRoute(start, end, next) {\n  console.log("calcRoute(\'" + start + "\',\'" + end + "\',next)");\n  var request = {\n    origin: start,\n    destination: end,\n    travelMode: \'BICYCLING\'\n  };\n  directionsService.route(request,\n    function(result, status) {\n      if (status == \'OK\') {\n\n        directionsDisplay = new google.maps.DirectionsRenderer({\n          suppressBicyclingLayer: true,\n          suppressMarkers: true,\n          preserveViewport: true // don\'t zoom to fit the route\n        });\n        directionsDisplay.setMap(map);\n        directionsDisplay.setDirections(result);\n        // combine the bounds of the responses\n        bounds.union(result.routes[0].bounds);\n        // zoom and center the map to show all the routes\n        map.fitBounds(bounds);\n      }\n      // ====== Decode the error status ======\n      else {\n        console.log("status=" + status + " (start=" + start + ", end=" + end + ")");\n        // === if we were sending the requests to fast, try this one again and increase the delay\n        if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {\n          nextAddress--;\n          delay += 100;\n          document.getElementById(\'delay\').innerHTML = delay;\n        } else {\n          var reason = "Code " + status;\n          var msg = \'start="\' + start + \' end="\' + end + \'"" error=\' + reason + \'(delay=\' + delay + \'ms)<br>\';\n          document.getElementById("messages").innerHTML += msg;\n        }\n      }\n      next();\n    });\n}\n
Run Code Online (Sandbox Code Playgroud)\r\n
var addresses = [\r\n  [\'243, Dornacherstrasse\', \'26, Mattenstrasse\'],\r\n  [\'48 av general de gaulle, saint louis\', \'Gr\xc3\xbcndenstra\xc3\x9fe 40, Muttenz\'],\r\n  [\'50 ackerstrasse , Basel\', \'holeestrasse 133, Basel\'],\r\n  [\'71 avenue de B\xc3\xa2le , Saint-Louis \', \'Leonhardstr 6, Basel\'],\r\n  [\'Ackerstrasse 44, Basel\', \'Petersplatz 1, Basel\'],\r\n  [\'Ackerstrasse 51, Basel\', \'Maiengasse 51, Basel \'],\r\n  [\'Aeussere Baselstr. 255, Riehen\', \'zu den drei Linden 80, Basel\'],\r\n  [\'Aeussere Baselstrasse 309, Riehen\', \'Gotthelfplatz 1, Basel\'],\r\n  [\'Ahornstrasse 20, Basel\', \'Viaduktstrasse , Basel\'],\r\n  [\'Albert Schweitzer Strasse 10, Basel\', \'Kohlenberg 17, Basel\'],\r\n  [\'alemannengasse 17, Basel\', \'Centrahlbahnplatz, Basel\'],\r\n  [\'Alemannengasse 23, Basel\', \'Peter Merian-Weg 8, Basel\'],\r\n  [\'Allmendstrasse 233, Basel\', \'Universit\xc3\xa4tsspital Basel, Basel \'],\r\n  [\'Allmendstrasse 4, Basel\', \'Petersplatz 1, Basel\'],\r\n  [\'Allschwilerstrasse 106, Basel\', \'Centralbahnstrasse 10 , Basel\'],\r\n  [\'Allschwilerstrasse 116, Basel\', \'Spitalstrasse 8, Architektur Institut, Basel \'],\r\n  [\'Allschwilerstrasse 116, Basel\', \'Steinenvorstadt 55, Kino Path\xc3\xa8 K\xc3\xbcchlin, Basel\'],\r\n  [\'Allschwilerstrasse 48, Basel\', \'Schneidergasse 28, Basel\'],\r\n  [\'Altrheinweg 52, Basel\', \'Vogesenplatz 1, Basel \'],\r\n  [\'Am Rheinpark 6, Weil am Rhein\', \'J. J. Balmer-Str. 3, Basel\'],\r\n  [\'Am Weiher 15, Binningen\', \'Klingelbergstrasse 82, Basel \'],\r\n  [\'Amerbachstrasse, , Basel\', \'Peter Merian-Weg, Basel\'],\r\n  [\'Amerikanerstrasse 16, Binningen\', \'Petersplatz 1, Basel\'],\r\n  [\'Amselweg 20, Reinach\', \'Baselstrasse 33, M\xc3\xbcnchenstein\'],\r\n  [\'An der Auhalde 15, Riehen\', \'Zu den Dreilinden 95, Basel\'],\r\n  [\'arnikastr. 22, Riehen\', \'marktplatz, Basel\'],\r\n  [\'Auf der Lyss 14, Basel\', \'Grenzstrasse 15, Basel\']\r\n];\r\n\r\nvar directionsDisplay;\r\nvar directionsService = new google.maps.DirectionsService();\r\nvar map;\r\nvar bounds;\r\n\r\nfunction initialize() {\r\n  directionsDisplay = new google.maps.DirectionsRenderer();\r\n  var basel = new google.maps.LatLng(41.850033, -87.6500523);\r\n  var mapOptions = {\r\n    zoom: 7,\r\n    center: basel\r\n  }\r\n  map = new google.maps.Map(document.getElementById(\'map\'), mapOptions);\r\n  directionsDisplay.setMap(map);\r\n  bounds = new google.maps.LatLngBounds();\r\n}\r\n\r\n// delay between directions requests\r\nvar delay = 100;\r\n\r\nfunction calcRoute(start, end, next) {\r\n  console.log("calcRoute(\'" + start + "\',\'" + end + "\',next)");\r\n  var request = {\r\n    origin: start,\r\n    destination: end,\r\n    travelMode: \'BICYCLING\'\r\n  };\r\n  directionsService.route(request,\r\n    function(result, status) {\r\n      if (status == \'OK\') {\r\n\r\n        directionsDisplay = new google.maps.DirectionsRenderer({\r\n          suppressBicyclingLayer: true,\r\n          suppressMarkers: true,\r\n          preserveViewport: true // don\'t zoom to fit the route\r\n        });\r\n        directionsDisplay.setMap(map);\r\n        directionsDisplay.setDirections(result);\r\n        // combine the bounds of the responses\r\n        bounds.union(result.routes[0].bounds);\r\n        // zoom and center the map to show all the routes\r\n        map.fitBounds(bounds);\r\n      }\r\n      // ====== Decode the error status ======\r\n      else {\r\n        console.log("status=" + status + " (start=" + start + ", end=" + end + ")");\r\n        // === if we were sending the requests to fast, try this one again and increase the delay\r\n        if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {\r\n          nextAddress--;\r\n          delay += 100;\r\n          document.getElementById(\'delay\').innerHTML = "delay between requests=" + delay;\r\n        } else {\r\n          var reason = "Code " + status;\r\n          var msg = \'start="\' + start + \' end="\' + end + \'"" error=\' + reason + \'(delay=\' + delay + \'ms)<br>\';\r\n          document.getElementById("messages").innerHTML += msg;\r\n        }\r\n      }\r\n      next();\r\n    });\r\n}\r\n\r\ninitialize();\r\n// ======= Global variable to remind us what to do next\r\nvar nextAddress = 0;\r\n\r\n// ======= Function to call the next Geocode operation when the reply comes back\r\n\r\nfunction theNext() {\r\n  if (nextAddress < addresses.length) {\r\n    console.log(\'call calcRoute("\' + addresses[nextAddress][0] + \'","\' + addresses[nextAddress][1] + \') delay=\' + delay);\r\n    setTimeout(\'calcRoute("\' + addresses[nextAddress][0] + \'","\' + addresses[nextAddress][1] + \'",theNext)\', delay);\r\n    nextAddress++;\r\n  } else {\r\n    // We\'re done. Show map bounds\r\n    map.fitBounds(bounds);\r\n  }\r\n}\r\n\r\n// ======= Call that function for the first time =======\r\ntheNext();\r\n\r\n// This Javascript is based on code provided by the\r\n// Community Church Javascript Team\r\n// https://www.bisphamchurch.org.uk/   \r\n// https://econym.org.uk/gmap/
Run Code Online (Sandbox Code Playgroud)\r\n
html,\r\nbody,\r\n#map {\r\n  height: 100%;\r\n  width: 100%;\r\n  margin: 0px;\r\n  padding: 0px\r\n}
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n


归档时间:

查看次数:

4876 次

最近记录:

6 年,11 月 前