-1

我在嘗試使用Google路線API生成路線。生成路由不是問題,但 我想通過在9小時或(32.400秒)內限制路由來加載路由點如何限制路線的時間?

我試着把它放在While(循環)中,過程計算但在處理Directions API時發生錯誤(Query Over limit) 有沒有人有任何想法?

我的代碼...

(function ($) { 
var directionDisplay; 
var directionsService = new google.maps.DirectionsService(); 
var map; 

var zoomLevel = 16; 
var idInfoBoxAberto; 
var infoBox = []; 
Markers = []; 
cor = '#0586e7'; 
indice = {}; 
customers = new Array(); 

var loc = ' - São Paulo,'; // Define location 
var registros = 1; 

function initialize() { 
    directionsDisplay = new google.maps.DirectionsRenderer({ suppressMarkers: true }); 

    var sp = new google.maps.LatLng(-23.6492, -46.6600); // Define center map (SP- Brasil) 

    var myOptions = { 
     zoom: 16, 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
     center: sp, 
     disableDefaultUI: true, 
     styles: [{ "stylers": [{ "saturation": -100 }, { "gamma": 1 }] }, { "elementType": "labels.text.stroke", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.business", "elementType": "labels.text", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.business", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.place_of_worship", "elementType": "labels.text", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.place_of_worship", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "road", "elementType": "geometry", "stylers": [{ "visibility": "simplified" }] }, { "featureType": "water", "stylers": [{ "visibility": "on" }, { "saturation": 50 }, { "gamma": 0 }, { "hue": "#50a5d1" }] }, { "featureType": "administrative.neighborhood", "elementType": "labels.text.fill", "stylers": [{ "color": "#333333" }] }, { "featureType": "road.local", "elementType": "labels.text", "stylers": [{ "weight": 0.5 }, { "color": "#333333" }] }, { "featureType": "transit.station", "elementType": "labels.icon", "stylers": [{ "gamma": 1 }, { "saturation": 50 }] }] 
    }; 

    map = new google.maps.Map(document.getElementById("google-map"), myOptions); 
    directionsDisplay.setMap(map); 

    calcRoute(' - São Paulo,'); 
} 

initialize(); 

function calcRoute(loc) { 

    $.getJSON('http://dbtraining.com.br/startup/app/maps/rota/' + loc, function (pontos) { 
     var RouteIndex = pontos[0].rota; 
     //console.log(RouteIndex); 

     $.each(pontos, function (index, ponto) { 

      if (RouteIndex != ponto.rota) { 
       RouteIndex = ponto.rota; 
       cor = getRandomColor(); 
      } 

      customers[registros] = { 
       "id": ponto.id, 
       "cliente": ponto.Cliente, 
       "endereco": ponto.endereco, 
       "territorio": ponto.Territorio, 
       "rota": ponto.rota, 
       "distance": ponto.distance, 
       "color": cor, 
       "lat": ponto.lat, 
       "lng": ponto.lng 
      }; 
      registros++; 
     }); 

     //Sort array by Distance 
     customers.sort(function (a, b) { 
      return (a.distance > b.distance) ? 1 : ((b.distance > a.distance) ? -1 : 0); 
     }); 

     var start = new google.maps.LatLng(customers[0].lat, customers[0].lng); 
     var end = new google.maps.LatLng(customers[0].lat, customers[0].lng); 

     var waypts = []; 
     var i = 1; 

     var distance = 0; 
     var time = 0; 
     var totaltime = 0; 

     // Load Waypoints. 
     while (i < 20) { 
      waypts.push({ location: customers[i].endereco, stopover: true }); 


      var request = { 
       origin: start, 
       destination: end, 
       waypoints: waypts, 
       optimizeWaypoints: true, 
       travelMode: google.maps.DirectionsTravelMode.WALKING 
      }; 

      directionsService.route(request, function (response, status) { 
       if (status == google.maps.DirectionsStatus.OK) { 
        directionsDisplay.setDirections(response); 

        var route = response.routes[0]; 

        for (var i = 0; i < route.legs.length; i++) { 
         var theLeg = route.legs[i]; 

         var marker = new google.maps.Marker({ 
          id: i, 
          position: route.legs[i].start_location, 
          map: map, 
          title: "Stop number: " + i, 
          icon: '../img/markers/marker.png', 
          label: { 
           text: i.toString() 
          } 
         }); 

         attachInfoWindow(marker, i, route.legs[i]); 

         time = theLeg.duration.value ; 
         totaltime += time + 5400; 

         console.log("ID.............: " + getKey(customers, "endereco", "R. Herculano de Freitas, 85 - Bela Vista, São Paulo - SP, 01308-020, Brasil")); 
         console.log("Start..........: " + theLeg.start_address); 
         console.log("Destination....: " + theLeg.end_address); 
         console.log("Location.......: " + theLeg.start_location.lat() + "," + theLeg.start_location.lng()); 
         console.log("Distance.......: " + theLeg.distance.text); 
         console.log("Travel time....: " + secondsToTime(theLeg.duration.value)); 
         console.log("Service time...: " + secondsToTime(5400)); 
         console.log(totaltime); 
         console.log("------------------------------"); 

        } 

        if (totaltime >= 32000) { 
         break; // break While Loop 
        } 

       } else { 
        alert("directions response " + status); 
       } 
      }); 

      sleep(1000); 
      i++; 
     } 
    }); //end getJSON 
} 




function secondsToTime(secs) { 
    secs = Math.round(secs); 
    var hours = Math.floor(secs/(60 * 60)); 

    var divisor_for_minutes = secs % (60 * 60); 
    var minutes = Math.floor(divisor_for_minutes/60); 

    var divisor_for_seconds = divisor_for_minutes % 60; 
    var seconds = Math.ceil(divisor_for_seconds); 

    var t = hours + ":" + minutes + ":" + seconds; 

    return t; 
} 

function sleep(milliseconds) { 
    var start = new Date().getTime(); 
    for (var i = 0; i < 1e7; i++) { 
     if ((new Date().getTime() - start) > milliseconds) { 
      break; 
     } 
    } 
} 

function getRandomColor() { 
    var length = 6; 
    var chars = 'ABCDEF'; 
    var hex = '#'; 
    while (length--) hex += chars[(Math.random() * 16) | 0]; 
    return hex; 
} 

function attachInfoWindow(marker, legIndex, leg) { 
    var infowindow = new google.maps.InfoWindow({ 
     content: "<div><h3>Stop Number: " + legIndex + "</h3><p>" + leg.start_address + "</p><a href='#'>(Stop Details)</a></div>" 
    }); 
    google.maps.event.addListener(marker, 'click', function() { //when the marker on map is clicked open info-window 
     infowindow.open(map, marker); 
     console.log(marker.get("id")); 
    }); 

} 

function getKey(obj, prop, val) { 
    var keys = []; 
    for (var key in obj) { 
     if (obj[key].hasOwnProperty(prop) && obj[key][prop] === val) { 
      keys.push(key); 
     } 
    } 
    return keys; 
} 

function dynamicSort(property) { 
    var sortOrder = 1; 
    if (property[0] === "-") { 
     sortOrder = -1; 
     property = property.substr(1); 
    } 
    return function (a, b) { 
     var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0; 
     return result * sortOrder; 
    } 
} 

})(window.jQuery);

回答

0

我沒看過完整的,但是:

// Load Waypoints. 
    while (i < 20) 
    ... 

無法工作,因爲方向服務僅限於8個航點一個請求。因此,您必須在達到此限制後開始新的請求,或者您要求從點到點。如果你在這裏搜索「多個航點」,你會發現很多解決方案的例子。

+0

當我在調用DirectionsService之前加載Waypoints時,路由處理沒有錯誤,但時間遠遠高於我的業務規則。 我知道DirectionsService限於多達23個航點。 我的問題是:加載航點,檢查時間,加載另一個航點並再次檢查時間,直到時間等於32000秒 –

0

當我在調用DirectionsService之前加載Waypoints時,路由處理沒有錯誤,但時間遠遠高於我的業務規則。

我知道DirectionsService限於多達23個航點。

我的問題是:加載一個航點,檢查時間,加載其他航點,並再次檢查的時間,直到時間等於32000秒

// Load Waypoints. 
     while (i < 20) { 
     waypts.push({ location: customers[i].endereco, stopover: true }); 
     i++; 
     } 

Route with 20 waypoints

鏈接JSON文件:http://dbtraining.com.br/startup/app/maps/rota/sp

+0

也許這只是一個時間問題。我認爲你的睡眠(1000)聲明不起作用。看看這個:http://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep – ReFran

+0

到時間限制的一般計算應該是相對簡單的。我寧願一步一步沒有航點。我把一個簡單的時間計算到我的例子(http://stackoverflow.com/questions/36023443/gmap-study-multi-auto-routes-direction-with-unlimited-waypoints-click-by-click)。您可以嘗試點擊示例是否適合您。如果你想根據你的需要來舉一個例子,請說明一些經緯度,作爲csv值。 Json會是一些額外的工作。 – ReFran