How to make markers in Leaflet blinking

14,811

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"); 
Share:
14,811
cartant
Author by

cartant

RxJS core team member; front-end developer; mentor; speaker; open-source contributor

Updated on June 26, 2022

Comments

  • cartant
    cartant almost 2 years

    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.

    • redshift
      redshift over 7 years
      I use animate.css in my projects. There is a blinking effect available.
  • Admin
    Admin over 7 years
    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.
  • cartant
    cartant over 7 years
    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.
  • Admin
    Admin over 7 years
    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?
  • Admin
    Admin over 7 years
    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");
  • Admin
    Admin over 7 years
    OK, it worked when I moved "L.DomUtil.addClass(startMarker._icon, "markerBlinking");" AFTER "map.setView()" call.
  • ingkevin
    ingkevin over 5 years
    @cartant marker does not have a property called _icon