Pergunta

I want to use direction Service (google maps API V3) between markers got from a search input with auto complete. i got the markers into an array but I can't get the position of the marker before the last one(markers[i-1]).

I get "Uncaught TypeError: Cannot read property 'position' of undefined " only for this one.

Whole code: https://stackoverflow.com/questions/23365667/get-directions-from-one-place-to-another-from-input

Why does this happen?

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);
        }
      });
    }    
Foi útil?

Solução

markers.length will (most likely) always be 1 or more. Therefore you'll get the error on every first cycle, markers[0-1] will always be undefined. Use

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

or

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

instead.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top