如果您想从 DirectionsRenderer 请求访问标记,则需要进行 hack,因为没有官方方法可以从 google 地图 api 执行此操作。
有一种方法可以解决,这是我做的一个例子:https://jsfiddle.net/TomKarachristos/cna78jbw/ https://jsfiddle.net/TomKarachristos/cna78jbw/
google.maps.event.addListener(directionsDisplay, 'directions_changed',
function() {
var self = this;
markersArray = []; //empty the array
setTimeout(function() { //wait until markers render
for (var k in self) { //search everything in directionsDisplay
if (typeof self[k].markers != 'undefined') { // its that the markers?
var markers = self[k].markers;
for (var i = 0; i < markers.length; ++i) {
markersArray.push(markers[i]);
markersArray[i].setLabel({ //lets change the label!
color: "white",
fontSize: "16px",
text: i.toString()
});
}
}
}
console.log(markersArray); // now markersArray have all the markers
}, 0);
});
但如果您想完全控制标记,这不是一个好的解决方案。如果你抑制标记,你有很多可能性,你可以使用像这样的库中的标记标记标签 http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.9/ or 丰富的标记 https://github.com/googlemaps/js-rich-marker(使用 dom 元素作为标记!)
这里是一个标记标签的示例,您单击地图中的任意位置,就会出现一个标记,其中带有与中心标记的距离的标签。https://jsfiddle.net/TomKarachristos/x1zg503m/ https://jsfiddle.net/TomKarachristos/x1zg503m/
[...]
markerArray[1] = new MarkerWithLabel({
position: location,
map: map,
animation: google.maps.Animation.DROP, //just for fun
labelContent: "",
labelClass: "marker-label"
});
[...]
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
route = directionsDisplay.getDirections().routes[0];
markerArray[1].set('labelContent', route.legs[0].distance.value / 1000)
[...]
more easy to make, more nice to see, more fun!