4

GoogleMapsDirectionsServiceに奇妙な問題があります。入力データが同じ場合は、異なるルートが返されます。これが私のコードのサンプルです

var path = [];
path.push(new google.maps.LatLng(51.10600101811778, 17.025117874145508));
path.push(new google.maps.LatLng(51.1047951799623,17.02278971672058));
path.push(new google.maps.LatLng(51.10456276619924, 17.02208161354065));
path.push(new google.maps.LatLng(51.10131895649719, 17.029248476028442));
path.push(new google.maps.LatLng(51.100331957810134, 17.033969163894653));
path.push(new google.maps.LatLng(51.10001867395775, 17.032413482666016));

for (var i = 0; i <path.length-1; i++) {
    var request = {
        origin: path[i],
        destination: path[i+1],
        travelMode: google.maps.DirectionsTravelMode.WALKING
    }

    directionsService.route(request, function(results, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            selected_path = selected_path.concat(results.routes[0].overview_path);
            poly.setPath(selected_path);
            poly.setMap(map);
        }
    })
}

呼び出し後の最初の関数は、開始点と終了点を常に接続する奇妙なポリラインを描画します。

2回目に呼び出されると、関数は正常に機能し、ルートが適切に描画されます。

これは、入力静的データの単なる例です。通常、私はマトリックスと動的マーカーの動的データを処理しますが、常に同じことが起こります。まず、始点が終点に接続されている+他の点間の奇妙な接続。2番目の呼び出し関数はうまく機能します。あなたの誰かがこの問題を解決する方法の手がかりを持っていますか?

4

2 に答える 2

9

これは単なる推測です。方向要求が非同期であるため、パスが順序どおりに連結されていないことが起こっていると思います。(データは必ずしも順番に返されるとは限りません)。以下で行ったことは、方向の各区間を配列に順番に配置し、配列を連続リストにフラット化して、適切な数のリクエストが正常に戻った後にのみ表示することです。

あなたのジグザグを再現できなかったので、この答えが本当に問題を解決するかどうかは正確にはわかりません。

// count number of directions requests that returned successfully
var count = 0;

for (var i = 0; i <path.length-1; i++) {
  var request = {
    origin: path[i],
    destination: path[i+1],
    travelMode: google.maps.DirectionsTravelMode.WALKING
  };

  // introduce variable scope to preserve value of i
  (function(i) {
     directionsService.route(request, function(results, status) {
       if (status == google.maps.DirectionsStatus.OK) {
         selected_path[i] = results.routes[0].overview_path;
         count++;

         // draw path only if all segments are completed
         if(count == path.length-1) {
           //flatten selected_path into 1-d array
           selected_path = Array.prototype.concat.apply([], selected_path);
           poly.setPath(selected_path);
           poly.setMap(map);
         }
       }
     });
   })(i);
 }
于 2012-05-20T15:38:43.967 に答える
0

私も同じ問題を抱えていました。タイマーで関数を呼び出し、250ミリ秒に設定すると、最良の結果が得られます。「for」ループでサービスを呼び出すと、この問題が発生します。

方法は次のとおりです。

//Counter for timer.
var counter2 = 0;

//Set a timer to pass latitude and longitude values to "draw_line()" function.
var timer = setInterval(function(){draw_way(new google.maps.LatLng(arrayLatitude[counter2], arrayLongitude[counter2]));

counter2 = counter2 + 1;

//Check if calue of timer is > "arrayLatitude.length" because if it becomes bigger it can't draw the way.


if(counter2 >= arrayLatitude.length)
{
    clearInterval(timer);


}
}, 250);
于 2013-10-13T06:08:29.950 に答える