How to make Google Maps V3 polyline snap to road from given points?

google-maps, google-maps-api-3, javascript

Solution

If you just want directions with waypoints, you should just call the directionsService once with those waypoints, something like this (not tested):

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

Note: there is a maximum of 8 waypoints with the free API.

Problem

I try to make a polyline snap to road from given marker points. My problem is, that the same code sometimes gives the good results, like in this image and sometimes a bad result, like this: Any ideas why this is hapenning? And also, is there a limitation for polyline snap to road? My map ini code: ``` 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); ``` My polyline route snap code: ``` 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); } }); } ```

Original source