Search code examples
javascriptgoogle-maps-api-3

How to solve “cannot call method … of undefined” error?


    function calcRoute() {
        var start = document.getElementById("start_").value;
        var end = document.getElementById("end_").value;
        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);
            }
        });
    }

Gives an error message in Chrome:

Uncaught TypeError: Cannot call method 'setDirections' of undefined

Could anyone suggest fixing this?


Solution

  • You are missing (global var)

    //var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer({ 'map': map }); 
    

    So directionsDisplay is undefined.