yavg yavg - 10 months ago 51
Javascript Question

Simple circle animation is only displayed the first time

I'm trying to put circles on a map every second. This animation consists of 4 circles that are shown once a point is added on the map.

enter image description here

After the first time the animation is not repeated again. I do not know why this happens. When new points are added, the animation does not happen again.

https://plnkr.co/edit/benkcHIINN9DCjvIvtEn?p=preview

var aNumCircles=[1,2,4,5];
function addpoints(){
//add circle on map
var coordenadas=map.latLngToLayerPoint([coordinates[cont].lat,coordinates[cont].long]);
svg.append('circle').attr("cx",coordenadas.x)
.attr("cy", coordenadas.y)
.attr("r", 1)
.style("fill",'red')
.attr("class",'circulo_mapa')
//add animation circles on map
var circle = svg.selectAll("circle").data(aNumCircles).enter().append('circle')
.attr("cx",coordenadas.x)
.attr("cy", coordenadas.y)
.attr("id", cont)
.attr("r", 0)

.style("stroke-width", function(d,i){ return 5 / (i+1) })
.attr("class", 'animation_explosion')
.transition()
.delay(function(d,i){ return Math.pow((i+1), 2.5) * 50 })
.duration(2000)
.ease('quad-in')
.attr("r", 25)
.style("stroke-opacity", 0)
.each("end", function (d,i) {
d3.select(this).remove();
});
cont++;
}
var interval = setInterval(function(){
addpoints();
if(cont==5){
clearInterval(interval);
}
},1000);

Answer Source

The problem is just the first line in this selection:

var circle = svg.selectAll("circle")
    .data(aNumCircles)
    .enter()
    .append("circle")
    //etc...

As there are already circles in the SVG at the second time addpoints() run, your "enter" selection will be empty.

Instead of that, it should be:

var circle = svg.selectAll(null)
    .data(aNumCircles)
    .enter()
    .append("circle")
    //etc...

By using selectAll(null) you can be completely sure that your "enter" selection has all the elements in your data array.

Here is the updated plunker: https://plnkr.co/edit/3u0er01thuj5P8e0XqO6?p=preview

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download