call an update function inside another function

I’ve messing around trying to draw circles of every earthquake in Peru taking into account the date.
But i want to refactor the code in two steps:

  • one calling a chart function as a initializer for the map boundaries:

peruMap = chart({
feature: features,
border: borders,
scale: quakeScale,
radius: “magnitude”,
color: “category”,
}
)

and two using an update function (inside chart) passing the updated data controlled by a Scrubber

peruMap.update(frames.get(date))

The chart function

function chart({
feature,
border,
scale,
radius,
color
} = {}) {

let value = null

const path = d3.geoPath(projection)

const svg = d3.create(‘svg’)
.attr(‘viewBox’, 0, 0, ${width}, ${height})

// Adding cartography
svg.append(‘g’)
.attr(‘fill’, ‘#ddd’)
.selectAll(‘path’)
.data(feature.features)
.enter().append(‘path’)
.attr(‘d’, path)

svg.append(‘path’)
.datum(border)
.attr(‘fill’, ‘none’)
.attr(‘stroke’, ‘white’)
.attr(‘stroke-linejoin’, ‘round’)
.attr(‘pointer-events’, ‘none’)
.attr(‘d’, path)

// Add data
let circle = svg.append(‘g’)
.attr(‘stroke-width’, 0.8)
.attr(‘fill-opacity’, 0.2)
.selectAll(‘circle’)

function update(data) {
circle = circle
.data(
frames.get(date)
.filter(([id, value]) => positions.has(id) && value > 0)
.sort(([, a], [, b]) => d3.descending(a, b)),
([id]) => id
)
.join(
enter => enter.append(“circle”)
.attr(‘cx’, d => projection([d.lon, d.lat])[0])
.attr(‘cy’, d => projection([d.lon, d.lat])[1])
.call(circle => circle.append(“title”))
)
.attr(‘stroke’, d => scale(d[color]))
.attr(‘fill’, d => scale(d[color]))
.attr(“r”, d => Math.pow( 1.5, d[radius]) * 1.5)
.call(circle => circle.select(“title”).text(([id, value]) => ${names.get(id)}\n${format(value)}))
}

return Object.assign(svg.node(), {update})
}

But it is not working, only the map is displayed. what am i doing wrong?
refactor the code in this notebook

I’ve sent you a suggestion to fix references to positions
https://observablehq.com/compare/f7b2753e7f6cabf8...86a5e66af783c9eb

1 Like

As always, thanks Fil.