4

我尝试从给定的标记点将折线捕捉到道路。我的问题是,相同的代码有时会产生好的结果,就像这张图片一样在此处输入图像描述

有时会产生不好的结果,例如: 在此处输入图像描述

任何想法为什么会发生这种情况?而且,折线捕捉到道路是否有限制?

我的地图ini代码:

var myLatlng = new google.maps.LatLng(47.6557, 23.5833);
var mapOptions = {
    zoom: 14,
    minZoom: 13,
    maxZoom: 19,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI:   true,
    overviewMapControl: false,
    streetViewControl:  false,
    scaleControl:       false,
    mapTypeControl:     false,
    panControl:         true,
    panControlOptions:{
        position: google.maps.ControlPosition.TOP_RIGHT
    },
    zoomControl: true,
    zoomControlOptions: {
        style: google.maps.ZoomControlStyle.LARGE,
        position: google.maps.ControlPosition.TOP_RIGHT
    }
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);

我的折线路线捕捉代码:

var polys = new google.maps.Polyline({
                map: map,
                strokeColor: "#5555FF"
            });
    myCoord = [
                        new google.maps.LatLng(47.663383463156144, 23.58100461977301),
                        new google.maps.LatLng(47.659221287827435, 23.586240291770082),
                        new google.maps.LatLng(47.65534785438211, 23.576713085349184),
                        new google.maps.LatLng(47.66020405359421, 23.572249889548402)
            ]; 

    // BEGIN: Snap to road
    var service = new google.maps.DirectionsService(),polys,snap_path=[];               
    polys.setMap(map);
    placeMarker(myCoord[0], map);
    for(j=0;j<myCoord.length-1;j++){            
            service.route({origin: myCoord[j],destination: myCoord[j+1],travelMode: google.maps.DirectionsTravelMode.DRIVING},function(result, status) {                
                if(status == google.maps.DirectionsStatus.OK) {                 
                      snap_path = snap_path.concat(result.routes[0].overview_path);
                      polys.setPath(snap_path);
                }        
            });
    }
4

1 回答 1

10

如果您只想要带有航点的方向,您应该使用这些航点调用一次方向服务,如下所示(未测试):

var service = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();    
directionsDisplay.setMap(map);

var waypts = [];
for(j=1;j<myCoord.length-1;j++){            
      waypts.push({location: myCoord[j],
                   stopover: true});
}

var request = {
    origin: myCoord[0],
    destination: myCoord[myCoord.length-1],
    waypoints: waypts,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
};

service.route(request,function(result, status) {                
    if(status == google.maps.DirectionsStatus.OK) {                 
          directionsDisplay.setDirections(result);
    } else { alert("Directions request failed:" +status); }
});

注意:免费 API 最多有 8 个航点。

于 2013-04-10T14:44:20.327 回答