如何实现Leaflet AwesomeMarkers整标记闪烁并访问标记修改属性
Leaflet标记整体闪烁及属性修改方案
一、实现整个标记闪烁
你之前将alarm-blink类添加到了AwesomeMarkers.icon的extraClasses中,这只会让图标部分闪烁。要让整个标记闪烁,需要把类添加到Marker实例上,而非图标组件。
修改后的代码:
static create(layer: MapViewLayer) { const alarmList: Array<AlarmData> = []; const colors: { [key: string]: string } = {}; colors['#d63e2a'] = 'red'; colors['#a23336'] = 'darkred'; colors['#ff8d7e'] = 'lightred'; colors['#f69730'] = 'orange'; colors['#ffca92'] = 'beige'; colors['#72af26'] = 'green'; colors['#728224'] = 'darkgreen'; colors['#b2ff59'] = 'lightgreen'; colors['#38aadd'] = 'blue'; colors['#0067a3'] = 'darkblue'; colors['#8adaff'] = 'lightblue'; colors['#ff91ea'] = 'pink'; colors['#d252b9'] = 'purple'; colors['#5b396b'] = 'darkpurple'; colors['#436978'] = 'cadetblue'; colors['#575757'] = 'gray'; colors['#a3a3a3'] = 'lightgray'; colors['#303030'] = 'black'; const markerColor = colors[ layer.options.icon?.options.markerColorHexa || '#38aadd' ] as L.AwesomeMarkers.AwesomeMarkersIconOptions['markerColor']; const markerIcon = L.AwesomeMarkers.icon({ prefix: layer.options.icon?.options.prefix as L.AwesomeMarkers.AwesomeMarkersIconOptions['prefix'], icon: layer.options.icon?.options.icon, markerColor: markerColor, }); // 判断是否需要启用闪烁 const shouldBlink = this.alarmBlink(layer, alarmList); // 将闪烁类添加到Marker实例的className选项中 const marker = new L.Marker(layer.latlng[0], { icon: markerIcon, className: shouldBlink ? 'alarm-blink' : '' }); return marker; }
配套CSS(确保动画覆盖整个标记):
.alarm-blink { animation: blink-animation 1s ease-in-out infinite alternate; } @keyframes blink-animation { 0% { opacity: 1; } 100% { opacity: 0.2; } }
二、访问标记修改属性
create方法返回的是L.Marker实例,只需保存该实例的引用,即可调用Leaflet Marker的API修改属性:
- 保存实例引用:
// 调用create方法后保存Marker实例 const targetMarker = YourStaticClass.create(yourLayer); // 如果需要添加到地图上 targetMarker.addTo(map);
- 常用属性修改方式:
- 修改闪烁状态:
// 添加闪烁类 targetMarker.setClassName('alarm-blink'); // 移除闪烁类 targetMarker.setClassName(''); // 或切换闪烁状态 targetMarker.getElement()?.classList.toggle('alarm-blink'); - 修改图标:
const newIcon = L.AwesomeMarkers.icon({ /* 新图标配置 */ }); targetMarker.setIcon(newIcon); - 修改位置:
targetMarker.setLatLng([newLat, newLng]); - 直接操作DOM元素:
const markerElement = targetMarker.getElement(); if (markerElement) { // 自定义样式或类 markerElement.style.transform = 'scale(1.2)'; }
内容的提问来源于stack exchange,提问作者ojoaovitoraraujo
相关产品推荐
相关产品推荐

