谷歌地图绘制路径工作到一定程度

时间:2013-03-25 12:51:49

标签: javascript google-maps google-maps-api-3

我有一个包含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);
                    });
                }                   

1 个答案:

答案 0 :(得分: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:无法读取属性'lat'未定义”的问题是由于您的逻辑。当您到达上次路线请求时,array [i + 1]不存在。试试这个:

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

example using function closure

将多个请求串在一起的

This example也可以帮到你。