0

latlang値の配列があり、この値に従うパスを描画したいと思います。これは私がしたことですが、それはある時点までしか描画しません。'result'をconsole.logすると、描画されたオブジェクトが期待され、出力されます

Uncaught Error: Error in property <routes>: (Cannot read property 'routes' of null)

function renderDirections(result) {

  var directionDisplay = new google.maps.DirectionsRenderer();
  directionDisplay.setMap(map);
  directionDisplay.setDirections(result);
  directionDisplay.setOptions({suppressMarkers: true});
}

for(var i=0; i < array.length; i++){

                    var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(array[i].lat, array[i].lng),
                    map: map                                 
                    });

                    var directionsService = new google.maps.DirectionsService();
                    directionsService.route({
                    origin:  new google.maps.LatLng(array[i].lat, array[i].lng),
                    destination:  new google.maps.LatLng(array[i+1].lat, array[i+1].lng),
                    unitSystem: google.maps.UnitSystem.IMPERIAL,
                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                    },
                    function(result){
                      renderDirections(result);
                    });
                }                   
4

1 に答える 1

0

DirectionsServiceの「ステータス」を確認してください。DirectionsServiceには、割り当てとレートの制限があります。

                directionsService.route({
                  origin:  new google.maps.LatLng(array[i].lat, array[i].lng),
                  destination:  new google.maps.LatLng(array[i+1].lat, array[i+1].lng),
                  unitSystem: google.maps.UnitSystem.IMPERIAL,
                  travelMode: google.maps.DirectionsTravelMode.DRIVING
                },
                function(result, status){
                  if (status == google.maps.DirectionsStatus.OK)
                    renderDirections(result);
                  else alert ("Directions request failed:"+status);
                });

「UncaughtTypeError:Undefinedのプロパティ'lat'を読み取れません」の問題は、ロジックが原因です。最後のルートリクエストに到達したとき、array [i+1]は存在しません。これを試して:

for(var i=0; i < array.length-1; i++){

関数クロージャを使用した例

複数のリクエストをつなぎ合わせるこの例も役立つ場合があります。

于 2013-03-25T13:27:17.973 に答える