我的 leaflet.js map 上有图钉,其中图像由它们所代表的对象的状态决定。例如,在线和离线用户 - 在线为绿色,离线为红色。我通过向 divIcon 添加一个类然后使用 css 控制图像来做到这一点。
我现在已将标记聚类添加到我的 map 中。我想要做的是根据集群内的多数状态'来确定集群的颜色。我的第一个想法是做这样的事情:
this.markers = L.markerClusterGroup({
iconCreateFunction: function(cluster) {
// Use this somehow to filter through and look at the pin elements
console.log(cluster.getAllChildMarkers());
return new L.DivIcon({ html: /* ?? */ });
}
});
但不幸的是,我无法从 getAllChildMarkers
返回的数组中访问 HTML 元素。
有人对我如何做到这一点有任何想法吗?或者获取 pin 的 HTML 元素的方法?
谢谢
编辑:
这里是我创建 map 引脚的地方(分配给我的主干模型的 mapPin
属性):
that.mapPins.org = L.divIcon({
className: 'org-div-icon',
html: "<div class='org-status "+ org.getGroupStatus() +"'></div>",
iconSize: [35, 35],
iconAnchor: [18, 17]
});
下面是我如何动态更改类:
$(model.get('mapPin')._icon).find('.org-status').attr('class', 'org-status ' + model.getGroupStatus());
我以为我可以像上面那样从 getAllChildMarkers
的返回中访问 _icon
,但它似乎不存在。
最佳答案
您可以使用 getAllChildMarkers
获取集群中的所有标记。有了标记后,您可以使用 marker.options.icon.options.className
访问它的类。您可以使用 marker.options.icon.options.html
这里有一些代码使用 underscore.js 函数来计算每个类的标记数量,找到最受欢迎的那个,并将该类用作聚类标记。
var markers = L.markerClusterGroup({
iconCreateFunction: function (cluster) {
var childMarkers = cluster.getAllChildMarkers();
// count how many there are of each class
var counts = _.countBy(childMarkers, function(marker) {
// class at icon level
//return marker.options.icon.options.className;
// class inside html
return $(marker.options.icon.options.html).attr('class');
});
// get the class with the highest count
var maxClass = _.invert(counts)[_.max(counts)];
// use this class in the cluster marker
return L.divIcon({ html: cluster.getChildCount(), className: maxClass });
},
});
关于javascript - 基于内部图标的传单簇颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22056750/