更改leaflet markercluster图标颜色,继承其余默认CSS属性

14

因此,我正在尝试更改leaflet地图中标记聚类图标的颜色。我只想改变颜色并继承其他默认属性(例如形状、文本属性等)。

这个示例中,有类似于我想要的东西,但他们定义了一个全新的CSS类,而没有使用默认图标样式。我需要的是像这样但带有自定义颜色:

输入图像描述

我知道我必须自定义iconCreateFunction。我正在尝试以下方法:

CSS

.foo { background-color: red;}
.bar { background-color: blue;}

JavaScript

var markers = L.markerClusterGroup({
    iconCreateFunction: function(cluster) {
        // here there is a piece code that determines the value of the variable 'class_name' is either foo or bar
        return L.divIcon({ className: "marker-cluster-medium "+class_name});
    }
});

很不幸,那个解决方案无效并导致图标渲染不美观。

我该如何仅更改默认markercluster图标的颜色?

2个回答

25

你的iconCreateFunction应该长得像这样

iconCreateFunction: function (cluster) {
 var childCount = cluster.getChildCount();
 var c = ' marker-cluster-';
 if (childCount < 10) {
   c += 'small';
 } 
 else if (childCount < 100) {
   c += 'medium';
 } 
 else {
   c += 'large';
 }

 return new L.DivIcon({ html: '<div><span>' + childCount + '</span></div>', 
  className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });
 }

并给CSS一些类似这样的东西

.marker-cluster-small {
background-color: rgba(218, 94, 94, 0.6);
}
.marker-cluster-small div {
background-color: rgba(226, 36, 36, 0.6);
}
.marker-cluster-medium {
background-color: rgba(241, 211, 87, 0.6);
}
.marker-cluster-medium div {
background-color: rgba(240, 194, 12, 0.6);
}

.marker-cluster-large {
background-color: rgba(253, 156, 115, 0.6);
}
.marker-cluster-large div {
background-color: rgba(241, 128, 23, 0.6);
}

请查看下面的 Plunker 以获取完整的工作示例:

https://plnkr.co/edit/GvDbB1rzIZ4bvIkQjM0p?p=preview


1
你好,这样做的话,你就没有默认的气泡图标了。我在原问题中添加了一张图片以进行澄清。 - floatingpurr
@floatingpurr 你有放置的图片的工作示例链接吗? - Punith Jain
1
是的,您可以在此处找到一个示例(https://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-realworld.388.html)。这是该库的默认行为。 - floatingpurr
1
你是否找到了如何保留默认的气泡等,只更改图标颜色的方法? - Mawg says reinstate Monica

2
很简单,只需在您的global.css或style.css文件中添加CSS即可。
.marker-cluster-small {
  background-color: #49afa5 !important;
}

.marker-cluster-small div {
  background-color: #1c9489 !important;
  color: #fff !important;
}

那将影响到所有集群组。OP希望其中一个成为默认值,另一个具有不同的颜色,以便区分。 - Mawg says reinstate Monica

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接