将动画添加到多路径PolyLine的问题

时间:2016-09-30 21:16:08

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

Demo

正如您所看到的那样,我将route导出为polyline并将其显示在地图上但您可以告诉我如何将动画添加到polyline之类{{} {3}}

以下是我的代码:

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

  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.962222),
    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: '#0000FF',
        strokeWeight: 3
      });
      var bounds = new google.maps.LatLngBounds();

      var legs = response.routes[0].legs;
      for (i = 0; i < legs.length; i++) {
        var steps = legs[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]);
          }
        }
      }

      polyline.setMap(map);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });

});

1 个答案:

答案 0 :(得分:1)

您提到的动画是通过逐个动态绘制折线的线段并使用setTimeout将标记移动到下一个线段的结束位置来完成的。

我已相应更新了您的小提琴,请参阅http://jsfiddle.net/gwhwf50t/1/

function moveMarker(map, marker, latlng) {
  marker.setPosition(latlng);
  map.panTo(latlng);
}

function autoRefresh(map, pathCoords) {
  var i, route, marker;

  route = new google.maps.Polyline({
    path: [],
    geodesic : true,
    strokeColor: '#0000FF',
    strokeWeight: 3,
    editable: false,
    map:map
  });

  marker = new google.maps.Marker({map:map, icon:"http://maps.google.com/mapfiles/ms/micons/blue.png"});

  for (i = 0; i < pathCoords.length; i++) {             
    setTimeout(function(coords) {
      route.getPath().push(coords);
      moveMarker(map, marker, coords);
    }, 200 * i, pathCoords[i]);
  }
}

...

directionsService.route({
  ...
  if (status === google.maps.DirectionsStatus.OK) {
    autoRefresh(map, response.routes[0].overview_path);
    ...