Google 地图 API 绘制行车路线,如果失败则绘制直线

Google maps API Draw driving route and if fail draw straight line

我正在尝试使用 google 地图 API 来绘制行车路线,但是当它失败时,例如他可以有一条穿越大海的路线(例如:中国到日本)和当它失败时我需要他直线更换行车路线。

问题是,当 API 找不到有效的解决方法时,柜员 "Hey if you fail I gonna just pick up destination value and draw a straight line to next point" 我不能,因为当它失败时回调函数 directionResult 是空的。

route(request:DirectionsRequest, callback:function(DirectionsResult, DirectionsStatus))

这就是我想要做的。这个例子如果运作良好,它应该在中国开 3 个点,然后直线到韩国,然后其他直线到韩国的其他点(在韩国不工作驾驶模式)然后其他直线到日本,然后从那里只是开车画画。

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

<script type="text/javascript">
var markers = [
        {
            "title": 'China1',
            "lat": '33.007',
            "lng": '120.504',
            "description": '1.'
        }
    ,
        {
            "title": 'China2',
            "lat": '32.304',
            "lng": '118.549',
            "description": '2'
        }
    ,
        {
            "title": 'China3',
            "lat": '38.161',
            "lng": '117.557',
            "description": '3'
        }
        ,
        {
            "title": 'SouthKorea1',
            "lat": '37.55',
            "lng": '126.989',
            "description": '4'
        }
        ,
        {
            "title": 'SouthKorea2',
            "lat": '35.91',
            "lng": '127.269',
            "description": '5'
        }
    ,
        {
            "title": 'Japan1',
            "lat": '34.17996',
            "lng": '131.5234',
            "description": '6'
        }
    ,
        {
            "title": 'Japan3',
            "lat": '35.0058',
            "lng": '132.3381',
            "description": '7'
        }
    ,
        {
            "title": 'Japan4',
            "lat": '35.06253',
            "lng": '134.0060087',
            "description": '8'
        }
    ,
        {
            "title": 'Japan5',
            "lat": '34.69974',
            "lng": '135.42779',
            "description": '9'
        }
    ,
        {
            "title": 'Japan6',
            "lat": '38.270',
            "lng": '140.866',
            "description": '10'
        }
];
window.onload = function () {
    var mapOptions = {
        center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
    var infoWindow = new google.maps.InfoWindow();
    var lat_lng = new Array();
    var latlngbounds = new google.maps.LatLngBounds(); //criar um rectagulo com o tamanho maximo com todos pontos
    for (var i = 0; i < markers.length; i++) {
        var data = markers[i];
        var myLatlng = new google.maps.LatLng(data.lat, data.lng);
        lat_lng.push(myLatlng);
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: data.title
        });
        latlngbounds.extend(marker.position); //extender os limites do rectagulo para os pontos
        (function (marker, data) {
            google.maps.event.addListener(marker, "click", function (e) {
                infoWindow.setContent(data.description);
                infoWindow.open(map, marker);
            });
        })(marker, data);
    }
    map.setCenter(latlngbounds.getCenter());
    map.fitBounds(latlngbounds); //definir limites

    //***********ROUTING****************//

    //Initialize the Path Array
    var path = new google.maps.MVCArray();

    //Initialize the Direction Service
    var service = new google.maps.DirectionsService(); //Serviço para computar direccoes entre 2 sitios

    //Set the Path Stroke Color
    var poly = new google.maps.Polyline({ map: map, strokeColor: '#235c23' });

    //Loop and Draw Path Route between the Points on MAP
    for (var i = 0; i < lat_lng.length; i++) {
        //if ((i) < lat_lng.length) {
            var src = lat_lng[i];
            var des = lat_lng[i + 1];
            poly.setPath(path); //add the ways to the polyine 
            service.route({
                origin: src,
                destination: des,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            }, function (result, status) {
                //alert(status);
                if (status == google.maps.DirectionsStatus.OK) {
                    len = result.routes[0].overview_path.length;
                    for (var j = 0; j < len; j++) {
                        path.push(result.routes[0].overview_path[j]);
                    }
                }else{
                    //if i could pass the value of  "var i" was easy
                    //path.push(src); //add points to the plyline

                }   
            });
        //}
    }
}
</script>

<div id="dvMap" style="width: 800px; height: 500px">
</div>

这里是Running Example

期望的结果(这是 geocodezip 答案的打印屏幕,我将图像添加到第一次来这个问题的人,以了解我当时想要什么。)

任何帮助将不胜感激:)

您需要的是 "closures",将其用作 route()

的回调函数
(function(i,s,d){
   return function (result, status) {

           if (status == google.maps.DirectionsStatus.OK) {
             len = result.routes[0].overview_path.length;
             for (var j = 0; j < len; j++) {
                path.push(result.routes[0].overview_path[j]);
             }
           }
           else{
                path.push(s); //add points to the plyline
           }    
}}(i,src,des))

你尝试的问题很明显,变量i、des和src将在循环内修改。

上面的函数调用将做什么:

它 returns 另一个函数(回调)。作为参数,变量将被传递。预期参数的名称是 i、s 和 d,您现在有 3 个新变量,它们也可以在返回的内部函数中使用(并且不会受到循环的影响)。

演示:http://jsfiddle.net/doktormolle/a93ntv0L/6/

但还有另一个问题:您总是将 latLngs 推到路径上,但您不能期望结果按所需顺序到达(它是 运行 异步)。你最好用段(当然是有序的)填充一个数组,当你得到所有结果时填充 path