-1

Google Directions API를 사용하여 경로를 생성하려고합니다. 경로를 생성하는 것은 문제가 아니지만 9 시간 또는 (32.400 초)에 경로를 제한하여 경로 점을로드하려고합니다.Route by Route는 어떻게 제한합니까?

While (루프) 안에 넣으려고했는데 프로세스가 시간이 있지만 길 찾기 API (검색어 초과 한도) 처리 중 오류가 발생했습니다. 누구에게 아이디어가 있습니까?

내 코드 ...

(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) 
    ... 

이 작동하지 않을 수 있습니다. 따라서이 한도에 도달하거나 새로운 지점을 요청할 때 새로운 요청을 시작해야합니다. 여기에서 "다중 경유지"를 검색하면 솔루션에 대한 많은 예제를 찾을 수 있습니다.

+0

DirectionsService를 호출하기 전에 Waypoint를로드하면 경로가 오류없이 처리되지만 시간은 비즈니스 규칙보다 훨씬 길어집니다. DirectionsService가 최대 23 개의 웨이 포인트로 제한된다는 것을 알고 있습니다. 내 문제는 : 웨이 포인트를로드하고, 시간을 확인하고, 다른 웨이 포인트를로드하고 시간이 32000 초와 같아 질 때까지 다시 확인하십시오. –

0

DirectionsService를 호출하기 전에 Waypoint를로드하면 경로가 오류없이 처리되지만 시간은 비즈니스 규칙보다 훨씬 길어집니다.

DirectionsService는 최대 23 개의 웨이 포인트로 제한된다는 것을 알고 있습니다.

내 문제입니다 : http://dbtraining.com.br/startup/app/maps/rota/sp : 시간이 32000 초

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

Route with 20 waypoints

링크와 동일 할 때까지 시간을 확인, 웨이 포인트를로드 다른 웨이 포인트를로드하고 다시 시간을 확인

+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