简体   繁体   中英

Is there a way to add a badge on marker in react-leaflet?

I have tried using ant design badge, normally it works when you put it on icon but no luck with react-leaflet marker. Here is what i have tried

<Badge count={5}>
  <Marker icon = {sideTipperIcon} position={[51.505, -0.09]}>
    <Tooltip direction='top'>
      Leading: Overload <br />
      Lagging: Utilization
    </Tooltip>
  </Marker>
</Badge>

In this scenario the badge does not show so is there any way to show a badge on this leaflet marker?

I am not sure if it can be achieved via the link you provided. You can construct your own badge marker component like this:

const MarkerWithBadge = props => {
  const initMarker = ref => {
    if (ref) {
      const popup = L.popup().setContent(props.children);
      ref.leafletElement
        .addTo(ref.contextValue.map)
        .bindPopup(popup, {
          className: "badge",
          closeOnClick: false,
          autoClose: false
        })
        .openPopup()
        // prevent badge from dissapearing onClick
        .off("click");
    }
  };
  return <Marker ref={initMarker} {...props} />;
};

badge css selector:

.badge .leaflet-popup-content {
  position: absolute;
  top: -5px;
  left: -12px;
  z-index: 10;
  min-width: 20px;
  width: 5px !important;
  height: 20px;
  padding: 0;
  color: #fff;
  font-weight: normal;
  font-size: 12px;
  line-height: 20px;
  white-space: nowrap;
  text-align: center;
  background: #f5222d;
  border-radius: 10px;
}

and use it like this:

<Map style={{ height: "100vh" }} center={position} zoom={this.state.zoom}>
     <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
     />
     <MarkerWithBadge position={position} icon={customMarker}>
       5
     </MarkerWithBadge>
</Map>

Demo

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