0

我有一个带有 latlang 值的数组,我想绘制一个遵循这个值的路径。这就是我所做的,但它只画到某个点。当我 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);
                });

“Uncaught TypeError: Cannot read property 'lat' of undefined”的问题是由于你的逻辑。当您收到最后一个路线请求时,array[i+1] 不存在。尝试这个:

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

使用函数闭包的示例

这个将多个请求串在一起的示例也可能对您有所帮助。

于 2013-03-25T13:27:17.973 回答