简体   繁体   中英

How to center a marker in a leaflet makers cluster spiderfy?

地图

The icon is displayed in the bottom cornor of blue shape. How can I align it in the center? It is not just one shape to control it via CSS. I have many shapes and each looking different.

The cluster is created using the following code:

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>`,
    });
  },
});

And the icons are created:

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);
}

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

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

Adding iconAnchor: [25, 25] fixed it.

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],
});

It is not always in the center but at least looking better than what I had before.

The ideal solution would be as @kboul suggested to get the polygon center and place the icon there, but not sure how to do this, since leaflet markers cluster creates polygons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM