How to make markers in Leaflet blinking
Asked Answered
G

1

7

Is there a simple way to make a marker in Leaflet map blinking ? I mean animated blinking - something like a loop of transition from opacity 1.0 to opacity 0.5 in 1 second and then reverse, end of loop.

Guillemot answered 26/1, 2017 at 22:23 Comment(1)
I use animate.css in my projects. There is a blinking effect available.Fosterfosterage
C
24

When you add a Marker you are able to specify an Icon - the options for which include a className. You can use this className option to animate the marker's icon via 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/[email protected]/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/[email protected]/dist/leaflet.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<div id="map"></div>

To toggle a marker from blinking to non-blinking, you can use Leaflet's DomUtil to add the blinking class to the marker's img element:

// 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"); 
Cottle answered 27/1, 2017 at 7:23 Comment(6)
Thanks, but is not exactly what I need. I need a marker to start blinking at some point. How do I access marker's icon and alter it's class name? I've been searching for this on the internet but I wasnt able to find answer.Guillemot
You can change a marker's icon at any time by calling setIcon, so just call that whenever you need to change between a non-blinking and blinking icon.Cottle
I know this method, however my preference is NOT to create new icon object again, but to access the icon and alter it's className. How to do this?Guillemot
I did it and I got : "TypeError: t is undefined" My code: var startMarker = L.marker( [startLat, startLng], { icon: startIcon } ); map.addLayer( startMarker ); L.DomUtil.addClass(startMarker._icon, "markerBlinking");Guillemot
OK, it worked when I moved "L.DomUtil.addClass(startMarker._icon, "markerBlinking");" AFTER "map.setView()" call.Guillemot
@Cottle marker does not have a property called _iconCarborundum

© 2022 - 2024 — McMap. All rights reserved.