Google Directions Service w/ Waypoints returning Z

2019-08-29 10:32发布

I currently have a DirectionsRenderer function that properly routes To and From fields on my page. After the routing is done I grab the overview_path and then load elements from a Fusion Table based on the path. Once this is done I've set up a listener looking for 'directions_changed', which would indicate a waypoint as such:

google.maps.event.addListener(directionsDisplay, 'directions_changed', function(){

        var wypnt = directionsDisplay.getDirections().routes[0].legs[0].via_waypoints.toString().match(/[^()]+/);
        wypnt.toString().split(",");
        wypnt = new google.maps.LatLng(wypnt[1],wypnt[0]);

        var waypoint = [];

        waypoint.push({ location: wypnt, stopover: true });

        route(waypoint);
    });

Once I pass it back to the route() function (the function that works normally with the To and From fields), I have this section of code:

if(waypoint){

    var request = {
        origin: document.getElementById("search-input-from").value,
        destination: document.getElementById("search-input-to").value,
        waypoints: waypoint,
        optimizeWaypoints: true,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
}
else{

    var request = {
        origin: document.getElementById("search-input-from").value,
        destination: document.getElementById("search-input-to").value,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
}

The rest of the code is based off the following if statement:

directionService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {

       //do stuff

     }
    else {
                alert("Directions query failed: " + status);
            }
    };

Unfortunately all I'm getting back is "Directions query failed: ZERO_RESULTS". Any idea why this is happening? I'm not sure if the way I'm forming the waypoint is wrong or something else.

1条回答
一纸荒年 Trace。
2楼-- · 2019-08-29 10:53

Some issues:

    wypnt.toString().split(",");

this will not have any effect to wypnt, split will not modify the original object. it has to be:

     wypnt = wypnt.toString().split(",");

Why are you switching latitude and longitude here?

    wypnt = new google.maps.LatLng(wypnt[1],wypnt[0]);

it has to be

   wypnt = new google.maps.LatLng(wypnt[0],wypnt[1]);

Most of all: why do you do it at all? you take an array, convert it to a string, split the string to get the original array.

Simply use:

 google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed', 
   function(){
   var waypoints=directionsDisplay.getDirections().routes[0]
                    .legs[0].via_waypoints||[];
    for(var i=0;i<waypoints.length;++i){
       waypoints[i]={stopover:true,location: waypoints[i]}
    }
    route(waypoints);
});

But note: when you redraw the route directions_changed will fire again.

查看更多
登录 后发表回答