沿路线添加标记

Posted

技术标签:

【中文标题】沿路线添加标记【英文标题】:Add Markers Along a Route 【发布时间】:2012-03-24 13:47:38 【问题描述】:

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

有什么建议吗?

【问题讨论】:

geocodezip.com/v3_kmMarkersFromDirections.html X marks along the direction的可能重复 【参考方案1】:

正如 Andrew 所说,航路点不会这样做。

您没有预定义的路线点(如示例),因此您可以做的是:

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

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

这是建议的实现:http://jsfiddle.net/doktormolle/eNzFb/


<edit>

请注意:此答案已过时。你最好改用内置的IconSequence。

【讨论】:

直到现在我才看到你的编辑,这个项目是我迄今为止放弃的一个项目。我希望我知道你编辑了你的回复,这样我就可以在很久以前看到这个。非常感谢您的精彩回答……这正是我想要的。【参考方案2】:

在路线服务返回的路线上每隔 1 英里放置一次标记的示例:

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

代码 sn-p:

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;
/* 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;
<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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

【讨论】:

【参考方案3】:

没有。如您所见,航点确定路线的路径。您想沿着确定的路径放置“航路点”。

这是可能的,Larry 在http://www.geocodezip.com/v3_polyline_example_kmmarkers.html 有一个例子

【讨论】:

以上是关于沿路线添加标记的主要内容,如果未能解决你的问题,请参考以下文章

沿着谷歌地图android中的路径动画汽车(标记)

如何在传单中的两个标记之间添加路线(折线)

在 Google 路线上添加 InfoWindow

如何沿同一垂直线对齐多个标记的内联块输入控件? [关闭]

使用弯道标记路线或路径的解决方案

google-maps kml,如何标记线串?