来自谷歌的所有折线上的标记都指向V3

时间:2016-10-28 06:34:34

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

你好,我有一个问题。

我绘制折线并在折线的每个点上设置标记。但是我的代码并没有为每一点设置标记。如下图所示,标记仅位于折线的某些部分。

如何在每条折线上设置标记?

enter image description here

function initMap() {
  var markerArray = [];
  // Instantiate a directions service.
  var directionsService = new google.maps.DirectionsService;
  // Create a map and center it on Manhattan.
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 3,
    center: {lat: 32.224759, lng: 60.298827},
  });
  // Create a renderer for directions and bind it to the map.
  var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
  // Instantiate an info window to hold step text.
  var stepDisplay = new google.maps.InfoWindow;
  // Display the route between the initial start and end selections.
  calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, stepDisplay, map);
  // Listen to change events from the start and end lists.
  var onChangeHandler = function() {
    calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, stepDisplay, map);
  };

  document.getElementById('start').addEventListener('change', onChangeHandler);
  document.getElementById('end').addEventListener('change', onChangeHandler);
  directionsDisplay.addListener('directions_changed', function() {
    computeTotalDistance(directionsDisplay.getDirections());
  });
}

function calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, stepDisplay, map) {
  // First, remove any existing markers from the map.
  for (var i = 0; i < markerArray.length; i++) {
    markerArray[i].setMap(null);
  }
  // Retrieve the start and end locations and create a DirectionsRequest using
  // DRIVING directions.
  directionsService.route({
    origin: document.getElementById('start').value,
    destination: document.getElementById('end').value,
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    // Route the directions and pass the response to a function to create
    // markers for each step.
    if (status === google.maps.DirectionsStatus.OK) {
      var polyline = new google.maps.Polyline({
        path: [],
        strokeColor: '#0000FF',
        strokeWeight: 3
      });
      var bounds = new google.maps.LatLngBounds();
      var legs = response.routes[0].legs;
      for (var i = 0; i < legs.length; i++) {
        var steps = legs[i].steps;
        for (var j = 0; j < steps.length; j++) {
          var nextSegment = steps[j].path;
          for (var k = 0; k < nextSegment.length; k++) {
            polyline.getPath().push(nextSegment[k]);
            var marker = markerArray[k] = markerArray[k] || new google.maps.Marker;
            marker.setPosition(nextSegment[k]);
            bounds.extend(nextSegment[k]);
            marker.setMap(map);
          }
        }
      }
      polyline.setMap(map);                 
      directionsDisplay.setDirections(response); 
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}

function computeTotalDistance(result) {
  var total = 0;
  var myroute = result.routes[0];
  for (var i = 0; i < myroute.legs.length; i++) {
    total += myroute.legs[i].distance.value;                    
  }
  total = total / 1000;
  document.getElementById('total').innerHTML = total + ' km';
}

1 个答案:

答案 0 :(得分:0)

我认为我在这段代码中发现了你的错误:

for (var i = 0; i < legs.length; i++) {
  ...
  for (var j = 0; j < steps.length; j++) {
    ...
    for (var k = 0; k < nextSegment.length; k++) {
      ...
      // Here you add the marker to the array if there is no marker set yet
      var marker = markerArray[k] = markerArray[k] || new google.maps.Marker;
      ...
    }
  }
}

你犯的错误是你只看数组的索引k。但是,每次for循环再次启动时,k的值都会重置为0。因此,您必须将数组的长度添加到索引:

for (var i = 0; i < legs.length; i++) {
  ...
  for (var j = 0; j < steps.length; j++) {
    ...
    for (var k = 0; k < nextSegment.length; k++) {
      ...
      // This is the real index you want to look at
      var marker = markerArray[markerArray.length + k] = markerArray[markerArray.length + k] || new google.maps.Marker;
      ...
    }
  }
}

但是,我认为实际上这样可以使您的代码更轻松,更易读:

for (var i = 0; i < legs.length; i++) {
  ...
  for (var j = 0; j < steps.length; j++) {
    ...
    for (var k = 0; k < nextSegment.length; k++) {
      ...
      // This looks much easier IMHO
      var marker = new google.maps.Marker;
      ...
      markerArray.push(marker);
    }
  }
}