Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fade in leaflet markers when added

Tags:

css

leaflet

My map loads icons from the API while scrolling around. The delay makes the markers pop into existence, which I don't like visually. Preferably, they would grow from a pixel to their normal size or fade in. I figured fade in wouldn't be too hard to do with css3 transitions. Markers have the method setOpacity(n) so I tried initializing the marker like

@marker = L.marker(
    coordinates,
    {opacity: .1}
).on('add', ->
    @setOpacity(1)
)

because I realized adding a marker was async so if I set the opacity too early, the transition wouldn't apply because the marker element wasn't in the DOM and the marker would render at full opacity. This is why I tried listening to the add event. But that doesn't work. apparently the event fires too early. If i put setOpacity in a timeout, it works fine. But I do not think that is a good way to write this, especially because it introduces even more delay on top of the API.

How can I fade in my icons? I think a lot of people want this feature, so maybe it would be a good leaflet plugin.

like image 298
light24bulbs Avatar asked Jan 10 '23 10:01

light24bulbs


1 Answers

This can be done by attaching a keyframe animation to the leaflet-marker-icon and leaflet-marker-shadow classes. The keyframe animation is what does the trick because it's selfinvoking, so you don't need to add any classes at runtime to start the animation. Animation works when the map is loaded with markers and when markers are added. Try the example below the code:

.leaflet-marker-icon,
.leaflet-marker-shadow {
  -webkit-animation: fadein 3s; /* Safari, Chrome and Opera > 12.1 */
  -moz-animation: fadein 3s; /* Firefox < 16 */
  -ms-animation: fadein 3s; /* Internet Explorer */
  -o-animation: fadein 3s; /* Opera < 12.1 */
  animation: fadein 3s;
}

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Firefox < 16 */
@-moz-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Internet Explorer */
@-ms-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Opera < 12.1 */
@-o-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

An example on Plunker: http://plnkr.co/edit/kw4zFqqbtfEFQzN4fg8U?p=preview

like image 181
iH8 Avatar answered Jan 24 '23 04:01

iH8