0

我目前有一个 DirectionsRenderer 函数,可以正确路由我页面上的 To 和 From 字段。路由完成后,我抓取了overview_path,然后根据路径从融合表中加载元素。完成此操作后,我设置了一个侦听器来寻找“directions_changed”,这将指示一个航路点:

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);
    });

一旦我将它传递回 route() 函数(与 To 和 From 字段一起正常工作的函数),我就有了这段代码:

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
    };
}

其余代码基于以下 if 语句:

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

       //do stuff

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

不幸的是,我得到的只是“路线查询失败:ZERO_RESULTS”。知道为什么会这样吗?我不确定我形成航点的方式是错误的还是其他的。

4

1 回答 1

1

一些问题:

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

这不会对 wypnt 产生任何影响,split 不会修改原始对象。它一定要是:

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

为什么要在这里切换经纬度?

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

它一定要是

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

最重要的是:你为什么要这样做?您获取一个数组,将其转换为字符串,拆分字符串以获取原始数组。

只需使用:

 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);
});

但请注意:当您重绘路线时,路线directions_changed将再次触发。

于 2013-12-18T00:19:53.483 回答