基于内部图标的传单簇颜色
-
22-12-2019 - |
题
我的 leaflet.js 地图上有图钉,其中图像由它们所代表的对象的状态确定。例如,在线和离线用户——在线为绿色,离线为红色。我通过向 divIcon 添加一个类,然后使用 css 控制图像来实现此目的。
我现在已将标记聚类添加到我的地图中。我想做的是通过以下方式确定簇的颜色 多数 集群内的状态。我的第一个想法是做这样的事情:
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: /* ?? */ });
}
});
但不幸的是我无法访问从返回的数组中的 HTML 元素 getAllChildMarkers
.
有人对我如何做到这一点有任何想法吗?或者获取 pin 的 HTML 元素的方法?
谢谢
编辑:
这是我创建地图图钉的地方(分配给我的骨干模型) 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());
我以为我能够访问 _icon
从返回 getAllChildMarkers
就像我上面做的那样,但它似乎不存在。
解决方案
您可以使用 getAllChildMarkers
获取簇中的所有标记。一旦你有了一个标记,你就可以访问它的类 marker.options.icon.options.className
. 。您可以使用以下命令访问 html 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 });
},
});
不隶属于 StackOverflow