使用Google Maps API v3将折线捕捉到道路

26
在Google Maps API V2中,这很容易实现。
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);

在 Google API V3 中,这种简单的方式不起作用。有类似方向服务的东西,但我不知道如何通过我的点绘制折线,并将折线捕捉到道路上。
2个回答

68

你在使用路线服务时走上了正确的道路。这是示例代码:

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

还可以查看我的工作示例:http://people.missouristate.edu/chadkillingsworth/mapsexamples/snaptoroad.htm


@chad-killingsworth 所以如果我理解正确的话,您通过在每次单击时调用DirectionsService并将所有结果存储在数组中来避免最大8个航点限制?假设我想自动显示每个1英里增量处的标记,类似于gmaps-pedometer.com;有没有使用API实现这个想法的想法? - Tobias J
抱歉,请忽略上面问题的后半部分;在这里找到了答案:https://dev59.com/sHE85IYBdhLWcg3wmEtW ..虽然不是很直接,而且似乎需要重新调整v3,但看起来可行... - Tobias J
2
Chad - 也许我漏掉了什么,但是你的工作示例似乎不允许绘制任何线条(左键移动地图视点;右键弹出浏览器上下文菜单)。 - user66001
如果我双击地图,线就会被很好地绘制出来。很棒的地图,做得好。 - Benjamin Oman
我正在尝试按照你的示例操作,但是不成功。http://stackoverflow.com/questions/29044948/add-and-remove-polylines-in-google-maps-api-v3 - Raza Ahmed
如何在静态地图URL中添加标记(例如&markers=color:red|label:D|54.5661310,-1.2505580)? - aldrien.h

3

如何在静态地图URL中添加标记(例如&markers=color:red|label:D|54.5661310,-1.2505580)? - aldrien.h

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接