无法从路线获取折线

时间:2016-09-28 17:24:59

标签: google-maps google-maps-api-3

我正在尝试在隐藏的路线(使用strokeWeight: 0)上设置折线动画并在此示例中为其设置动画,但不确定为什么我无法在.interpolate()方法上获取正确的点。

请你看一下代码,让我知道我做错了什么?

  <script src="https://maps.googleapis.com/maps/api/js?key=xxx&libraries=geometry"></script>

var map;
$(document).ready(function() {
  var latlng = new google.maps.LatLng(49.241943, -122.889318);
  var myOptions = {
    zoom: 12,
    center: latlng,
    disableDefaultUI: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map($('#map_canvas').get(0), myOptions);
  //Starting Direction Services

  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer({
    map: map,
    preserveViewport: true
  });

  directionsService.route({
    origin: new google.maps.LatLng(49.241943, -122.889318),
    destination: new google.maps.LatLng(49.241943, -122.999999),
    waypoints: [{
      stopover: false,
      location: new google.maps.LatLng(49.241943, -122.889318)
    }],
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      // directionsDisplay.setDirections(response);
      var polyline = new google.maps.Polyline({
        path: [],
        strokeColor: 'red',
        strokeWeight: 0
      });
      var bounds = new google.maps.LatLngBounds();


      var line = response.routes[0].legs;
      for (i = 0; i < polyline.length; i++) {
        var steps = polyline[i].steps;
        for (j = 0; j < steps.length; j++) {
          var nextSegment = steps[j].path;
          for (k = 0; k < nextSegment.length; k++) {
            polyline.getPath().push(nextSegment[k]);
            bounds.extend(nextSegment[k]);
          }
        }
      }
      var step = 0;
      var numSteps = 250;
      var timePerStep = 5;
      var interval = setInterval(function() {
        step += 1;
        if (step > numSteps) {
          clearInterval(interval);
        } else {
          var are_we_there_yet = google.maps.geometry.spherical.interpolate(line, step / numSteps);
          line.setPath([polyline, are_we_there_yet]);
        }
      }, timePerStep);
      line.setMap(map);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });


});

1 个答案:

答案 0 :(得分:0)

interpolate函数根据the docs

获取这三个参数
  • 来自:LatLng,
  • to:LatLng,
  • 分数:数字

您将以下两个参数传递给它:

google.maps.geometry.spherical.interpolate(line, step / numSteps)

而不是传递整个line,你应该做的事情如下:

google.maps.geometry.spherical.interpolate(latLng1, latLng2, step / numSteps)

...其中latLng1和latLng2将是你的线的端点我猜。

您也是这样做的......您创建了一条折线,polyline。然后你得到一个line。但是你试着循环polyline.length

  var polyline = new google.maps.Polyline({
    path: [],
    strokeColor: 'red',
    strokeWeight: 0
  });

  var line = response.routes[0].legs;
  for (i = 0; i < polyline.length; i++) {

我认为最后一行(以及嵌套循环中的其他引用)应该引用line而不是polyline,即

for (i = 0; i < line.length; i++) {