调用标记数组中最后一个标记之前的标记位置

Call the position of the marker before the last one in an array of markers

本文关键字:位置 数组 调用 最后一个      更新时间:2023-09-26

我想在自动完成的搜索输入的标记之间使用方向服务(google maps API V3(。我把标记放进了一个数组,但我无法得到最后一个(标记[i-1](之前标记的位置。

我只得到了这一个的"未捕获类型错误:无法读取未定义的属性'position'"。

完整代码:https://stackoverflow.com/questions/23365667/get-directions-from-one-place-to-another-from-input

为什么会发生这种情况?

for (var i = 0; i < markers.length; i++) {
            if (markers.length > 1) {   
                place = markers[i].position;
                console.log(place);
                lastPlace = markers[i-1].position;
                console.log(lastPlace);         
                calcRoute();
            }
        }
function calcRoute() {

         var start = lastPlace;
        var end = place;
        console.log(start);
        console.log(end);
        var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.TravelMode.DRIVING
      };
      directionsService.route(request, function(response, status) {
        if (status === google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
      });
    }    

markers.length(很可能(总是1或更大。因此,您将在每个第一个循环中得到错误,markers[0-1]将始终未定义。使用

if (i > 0) {   
    place = markers[i].position;
    console.log(place);
    lastPlace = markers[i-1].position;
    console.log(lastPlace);         
    calcRoute();
}

for (var i = markers.length; i>1; i--) {
    place = markers[i].position;
    console.log(place);
    lastPlace = markers[i-1].position;
    console.log(lastPlace);         
    calcRoute();
}

相反。