代码之家  ›  专栏  ›  技术社区  ›  samvdst

Google Maps JavaScript API V3-显示多条路线[重复]

  •  1
  • samvdst  · 技术社区  · 7 年前

    我正在尝试使用谷歌地图API显示多条路线。 但当尝试10条以上的路线时,我会遇到OVER\u QUERY\u LIMIT异常。

    我发现,使用google时,我需要使用回调函数异步调用DirectionsDisplay(目前还无法实现)。我必须使用某种超时,因为每秒不能发出超过10个请求。

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

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

    我知道在这方面有很多类似的问题。但没有一个对我有用。

    1 回复  |  直到 7 年前
        1
  •  6
  •   geocodezip    6 年前

    使用相关答案中的修改代码 OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down? 它通过检测OVER\u QUERY\u LIMIT状态并增加请求之间的延迟来解决Google Maps Javascript API v3地理编码器的相同问题。

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

    proof of concept fiddle

    screenshot of resulting map

    代码段:

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