首页 > 解决方案 > 如何在传单制造商集群 spiderfy 中居中标记?

问题描述

地图

图标显示在蓝色形状的底角。我怎样才能将它对齐在中心?通过 CSS 控制它不仅仅是一种形状。我有很多形状,每个看起来都不一样。

使用以下代码创建集群:

this.stationMarkers = L.markerClusterGroup({
  iconCreateFunction: function (cluster) {
    const icons = [], temps = [];
    const markers = cluster.getAllChildMarkers();

    for (let i = 0; i < markers.length; i++) {
      if (markers[i]['Tavg']) temps.push((markers[i]['Tavg']));
      if (markers[i]['Icon']) icons.push((markers[i]['Icon']));
    }

    return L.divIcon({
      html: `<img src=\'./assets/images/icons-png/${icons.length > 0 ? math.mode(icons)[0] : ''}.png\'
              width="50px"/>
             <span>${(math.sum(temps) / temps.length).toFixed(1) + '°C'}</span>`,
    });
  },
});

并创建图标:

for (const d of this.data) {
  const icon = new L.DivIcon({
    html: `<img src='./assets/images/icons-png/${d.icon}.png' width="50px"/>
              <span>${d.Temp + '°C'}</span>`,
  });

  const marker = L.marker([d.Latitude, d.Longitude], {icon});
  marker['Tavg'] = d.Temp;
  marker['Icon'] = d.icon;

  this.stationMarkers.addLayer(marker);

  latitudes.push(d.Latitude);
  longitudes.push(d.Longitude);
}

包:https ://github.com/Leaflet/Leaflet.markercluster

示例:https ://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-realworld-maxzoom.388.html

标签: javascriptleafletleaflet.markercluster

解决方案


添加iconAnchor: [25, 25]修复它。

return L.divIcon({
  html: `<img src=\'./assets/images/icons-png/${icons.length > 0 ? math.mode(icons)[0] : ''}.png\'
          width="50px"/>
         <span>${(math.sum(temps) / temps.length).toFixed(1) + '°C'}</span>`,
  iconAnchor: [25, 25],
});

它并不总是在中心,但至少看起来比我以前的更好。

理想的解决方案是@kboul 建议获取多边形中心并将图标放在那里,但不确定如何执行此操作,因为传单标记群集会创建多边形。


推荐阅读