如何使Leaflet地图中的标记闪烁

7
有没有一种简单的方法使Leaflet地图中的标记闪烁?我的意思是动画闪烁-类似于在1秒钟内从不透明度1.0到不透明度0.5的过渡循环,然后反向,循环结束。

1
我在我的项目中使用animate.css。有一个可用的闪烁效果。 - redshift
1个回答

20
当您添加一个 Marker 时,可以指定一个 Icon - 其选项包括一个 className。您可以使用此 className 选项通过 CSS 动画来显示标记的图标。

var map = L.map('map').setView([51.505, -0.09], 13);

L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors',
  maxZoom: 18
}).addTo(map);

L.marker([51.5, -0.09], {
  icon: L.icon({
    iconUrl: 'https://unpkg.com/leaflet@1.0.3/dist/images/marker-icon.png',
    className: 'blinking'
  })
}).addTo(map);
#map {
  bottom: 0;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
}

@keyframes fade { 
  from { opacity: 0.5; } 
}

.blinking {
  animation: fade 1s infinite alternate;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
<div id="map"></div>

为了将标记从闪烁变为不闪烁,您可以使用Leaflet的DomUtil向标记的img元素添加blinking类:
// With the class added, the marker will blink:
L.DomUtil.addClass(marker._icon, "blinking");

// Without the class, it won't:
L.DomUtil.removeClass(marker._icon, "blinking"); 

谢谢,但不完全是我需要的。我需要一个标记在某个时刻开始闪烁。如何访问标记的图标并更改其类名?我已经在互联网上搜索了这个问题,但是没有找到答案。 - user6787244
您可以随时通过调用setIcon更改标记的图标,因此只需在需要在非闪烁和闪烁图标之间切换时调用该函数即可。 - cartant
我知道这种方法,但是我的偏好不是再创建一个新的图标对象,而是访问该图标并更改其className。如何做到这一点? - user6787244
我做了,然后出现了这个错误:"TypeError: t is undefined"。 我的代码: var startMarker = L.marker([startLat, startLng], { icon: startIcon }); map.addLayer(startMarker); L.DomUtil.addClass(startMarker._icon, "markerBlinking"); - user6787244
1
当我将 "L.DomUtil.addClass (startMarker._icon,"markerBlinking");" 放在 "map.setView ()" 调用之后时,它可以工作。 - user6787244
@cartant标记没有名为_icon的属性。 - ingkevin

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