26

In google maps api v2 it was easy,

var map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(53.7877, -2.9832),13)
//    map.addControl(new GLargeMapControl());
//    map.addControl(new GMapTypeControl());
    var dirn = new GDirections();

//      var firstpoint = true;
    var gmarkers = [];
    var gpolys = [];
    var dist = 0;

// == When the user clicks on a the map, get directiobns from that point to itself ==

gmarkers.push(new google.maps.LatLng(53.7877, -2.9832));
gmarkers.push(new google.maps.LatLng(53.9007, -2.9832));
gmarkers.push(new GLatLng(53.600, -2.700));



for (var i = 0; i < gmarkers.length-1; i++) {
    console.log(gmarkers[i]);
                dirn.loadFromWaypoints([gmarkers[i].toUrlValue(6),gmarkers[i+1].toUrlValue(6)],{getPolyline:true});

}


// == when the load event completes, plot the point on the street ==
    GEvent.addListener(dirn,"load", function() {
// snap to last vertex in the polyline
        var n = dirn.getPolyline().getVertexCount();
            map.addOverlay(dirn.getPolyline());
            gpolys.push(dirn.getPolyline());
            dist += dirn.getPolyline().getDistance();
            document.getElementById("distance").innerHTML="Path length: "+(dist/1000).toFixed(2)+" km. "+(dist/1609.344).toFixed(2)+" miles.";
           });
    GEvent.addListener(dirn,"error", function() {
        GLog.write("Failed: "+dirn.getStatus().code);
    });
console.log(dirn);

In google api V3 this way simple doesnt work. There is something like directions service but I dont have any idea how I can draw polyline through my points and polyline will be snaped to road.

Kara
  • 6,115
  • 16
  • 50
  • 57
Martus0
  • 667
  • 1
  • 10
  • 16

2 Answers2

68

You were on the right track with the directions service. Here's sample code:

var map, path = new google.maps.MVCArray(),
    service = new google.maps.DirectionsService(), poly;

function Init() {
  var myOptions = {
    zoom: 17,
    center: new google.maps.LatLng(37.2008385157313, -93.2812106609344),
    mapTypeId: google.maps.MapTypeId.HYBRID,
    mapTypeControlOptions: {
      mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID,
          google.maps.MapTypeId.SATELLITE]
    },
    disableDoubleClickZoom: true,
    scrollwheel: false,
    draggableCursor: "crosshair"
  }

  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  poly = new google.maps.Polyline({ map: map });
  google.maps.event.addListener(map, "click", function(evt) {
    if (path.getLength() === 0) {
      path.push(evt.latLng);
      poly.setPath(path);
    } else {
      service.route({
        origin: path.getAt(path.getLength() - 1),
        destination: evt.latLng,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
      }, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          for (var i = 0, len = result.routes[0].overview_path.length;
              i < len; i++) {
            path.push(result.routes[0].overview_path[i]);
          }
        }
      });
    }
  });
}

Also, see my working example: http://people.missouristate.edu/chadkillingsworth/mapsexamples/snaptoroad.htm

Chad Killingsworth
  • 14,360
  • 2
  • 34
  • 57
  • @chad-killingsworth so if I'm reading this correctly, you get around the maximum 8 waypoints limitation, by calling the DirectionsService with each click, and then storing all those results in an array? Let's say I wanted to automatically show a marker at every 1-mile increment, similar to gmaps-pedometer.com; any idea how to do that using the API? – Tobias J Mar 07 '13 at 03:11
  • Sorry, disregard the 2nd half of the above question; found the answer here: http://stackoverflow.com/questions/2698112/how-to-add-markers-on-google-maps-polylines-based-on-distance-along-the-line .. not exactly straightforward and it looks like it needs to be reworked for v3 but it looks do-able... – Tobias J Mar 07 '13 at 03:21
  • 2
    Chad - Perhaps I am missing something, but your working example doesn't seem to allow drawing any lines (Left click moves map viewpoint; Right click brings up browser context menu). – user66001 Feb 06 '14 at 15:56
  • If I double-click on the map the lines draw just fine. Cool map, well done. – Benjamin Oman May 08 '14 at 07:12
  • I'm trying to follow your example but unsuccessful.. http://stackoverflow.com/questions/29044948/add-and-remove-polylines-in-google-maps-api-v3 – Raza Ahmed Mar 14 '15 at 03:03
  • how to add markers (e.g. &markers=color:red|label:D|54.5661310,-1.2505580) in static map url? – aldrien.h Oct 12 '17 at 09:31
3

Its better to use Snap to Roads API, and set interpolate to true to get perfect snaped polyline. https://developers.google.com/maps/documentation/roads/snap