沿路线添加标记

时间:2012-03-07 01:36:38

标签: google-maps-api-3 routes google-maps-markers directions

我正在尝试沿着谷歌地图方向的路线创建几个标记。我已经考虑过航点作为一种选择,但根据我对其上的文档的理解,它创建了从A点到B点的路线,并通过您设置的航路点,以便从A点到达B点。不希望我的路线根据预定的航路点计算。我想要一个预定的起点和终点,我的航路点是根据地图上的距离计算的。例如,沿路线每隔许多英里创建一个标记。路点会这样做吗?如果是这样,那么已经完成了哪些例子?

有什么建议吗?

3 个答案:

答案 0 :(得分:6)

正如安德鲁所说,路标不会这样做。

您没有路线的预定义点(如eaxmple),所以您可以做的是:

方向由route-> overview_path定义的点组成,这些点定义了路径的折线。

因此,您可以走这条路,使用google.maps.geometry.spherical.computeDistanceBetween()计算两个路径点之间的距离,并在达到所需距离时创建标记。

以下是该建议的实施:http://jsfiddle.net/doktormolle/eNzFb/


<强> <edit>

请注意:这个答案已经过时了。您最好使用内置的IconSequence

答案 1 :(得分:1)

沿路线服务返回的路线每隔1英里放置标记的示例:

http://www.geocodezip.com/v3_kmMarkersFromDirections.html

enter image description here

代码段

&#13;
&#13;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var polyline = null;
var gmarkers = [];
var infowindow = new google.maps.InfoWindow();

function initMap() {
  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer;
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: {
      lat: 41.85,
      lng: -87.65
    }
  });
  polyline = new google.maps.Polyline({
    path: [],
    strokeColor: '#FF0000',
    strokeWeight: 3
  });


  directionsDisplay.setMap(map);
  calculateAndDisplayRoute(directionsService, directionsDisplay);
  var onChangeHandler = function() {
    calculateAndDisplayRoute(directionsService, directionsDisplay);
  };
  document.getElementById('btn').addEventListener('click', onChangeHandler);
}

function calculateAndDisplayRoute(directionsService, directionsDisplay) {
  directionsService.route({
    origin: document.getElementById('start').value,
    destination: document.getElementById('end').value,
    travelMode: 'DRIVING'
  }, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      polyline.setPath([]);
      var bounds = new google.maps.LatLngBounds();
      startLocation = new Object();
      endLocation = new Object();
      directionsDisplay.setDirections(response);
      var route = response.routes[0];
      // For each route, display summary information.
      var path = response.routes[0].overview_path;
      var legs = response.routes[0].legs;
      for (i = 0; i < legs.length; i++) {
        if (i == 0) {
          startLocation.latlng = legs[i].start_location;
          startLocation.address = legs[i].start_address;
          // marker = google.maps.Marker({map:map,position: startLocation.latlng});
          marker = createMarker(legs[i].start_location, "start", legs[i].start_address, "green");
        }
        endLocation.latlng = legs[i].end_location;
        endLocation.address = legs[i].end_address;
        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);
      for (var i = 0; i < gmarkers.length; i++) {
        gmarkers[i].setMap(null);
      }
      gmarkers = [];
      var points = polyline.GetPointsAtDistance(1000);
      for (var i = 0; i < points.length; i++) {
        var marker = new google.maps.Marker({
          map: map,
          position: points[i],
          title: i + 1 + " mile"
        });
        marker.addListener('click', openInfoWindow);
      }

    } else {
      alert("directions response " + status);
    }
  });


  /*  function(response, status) {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    }); */
}
google.maps.event.addDomListener(window, 'load', initMap);

function createMarker(latlng, label, html, color) {
  // alert("createMarker("+latlng+","+label+","+html+","+color+")");
  var contentString = '<b>' + label + '</b><br>' + html;
  var marker = new google.maps.Marker({
    position: latlng,
    // draggable: true, 
    map: map,
    icon: getMarkerImage(color),
    title: label,
    zIndex: Math.round(latlng.lat() * -100000) << 5
  });
  marker.myname = label;
  gmarkers.push(marker);

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(contentString);
    infowindow.open(map, marker);
  });
  return marker;
}
var icons = new Array();
icons["red"] = {
  url: "http://maps.google.com/mapfiles/ms/micons/red.png"
};

function getMarkerImage(iconColor) {
  if ((typeof(iconColor) == "undefined") || (iconColor == null)) {
    iconColor = "red";
  }
  if (!icons[iconColor]) {
    icons[iconColor] = {
      url: "http://maps.google.com/mapfiles/ms/micons/" + iconColor + ".png"
    };
  }
  return icons[iconColor];

}

function openInfoWindow() {
  var contentString = this.getTitle() + "<br>" + this.getPosition().toUrlValue(6);
  infowindow.setContent(contentString);
  infowindow.open(map, this);
}

// === A method which returns an array of GLatLngs of points a given interval along the path ===
google.maps.Polyline.prototype.GetPointsAtDistance = function(metres) {
  var next = metres;
  var points = [];
  // some awkward special cases
  if (metres <= 0) return points;
  var dist = 0;
  var olddist = 0;
  for (var i = 1;
    (i < this.getPath().getLength()); i++) {
    olddist = dist;
    dist += google.maps.geometry.spherical.computeDistanceBetween(this.getPath().getAt(i), this.getPath().getAt(i - 1));
    while (dist > next) {
      var p1 = this.getPath().getAt(i - 1);
      var p2 = this.getPath().getAt(i);
      var m = (next - olddist) / (dist - olddist);
      points.push(new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m));
      next += metres;
    }
  }
  return points;
}
&#13;
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

html,
body,
#map {
  height: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto', 'sans-serif';
  line-height: 30px;
  padding-left: 10px;
}
&#13;
<div id="floating-panel">
  <b>Start: </b>
  <input id="start" value="New York, NY" />
  <b>End: </b>
  <input id="end" value="Newark, NJ" />
  <input id="btn" value="Get Directions" type="button" />
</div>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

没有。正如您所发现的,航路点确定路线的路径。您希望沿路线放置“航点”,无论哪条路径确定。

有可能,拉里在http://www.geocodezip.com/v3_polyline_example_kmmarkers.html

有一个例子