如何为Datamaps插件中的气泡添加ID,以通过d3.select("#my_bubble_id")访问单个气泡
Got it, let's get this sorted so you can target individual bubbles with d3.select("#my_bubble_id"). Here's a straightforward, step-by-step solution:
Step 1: Add a unique ID field to your bubble data
First, add an id property to each object in your bombs array. Make sure the ID follows HTML rules—no spaces, use underscores or hyphens if needed:
var bombs = [{ id: 'tsar_bomba', // Unique ID for the bubble name: 'Tsar Bomba', radius: 1, yeild: 50000, country: 'USSR', fillKey: 'RUS', significance: 'Largest thermonuclear weapon ever tested—scaled down from its initial 100 Mt design by 50%', date: '1961-10-31', latitude: 40.8499966, longitude: 129.666664 }];
Step 2: Draw bubbles, then assign IDs using D3
Datamaps doesn’t have a built-in setting to add bubble IDs directly, but since it’s built on D3, we can add the IDs right after rendering the bubbles.
After calling map.instance.bubbles(), select all bubble elements (they use the class datamaps-bubble), then loop through them to set the id attribute using the bound data:
// Draw bubbles as you normally would map.instance.bubbles(bombs, { popupTemplate:function (geography, data) { return ['<div class="hoverinfo"><strong>' + data.name + '</strong>', '<br/>Payload: ' + data.yeild + ' kilotons', '<br/>Country: ' + data.country + '', '<br/>Date: ' + data.date + '', '</div>'].join(''); } }); // Assign IDs to each bubble element d3.selectAll('.datamaps-bubble') .each(function(d) { // `d` refers to the original data object from your bombs array d3.select(this).attr('id', d.id); });
Step 3: Target your bubble directly
Now you can access the specific bubble using its ID like this:
d3.select("#tsar_bomba")
This works because every Datamaps bubble is bound to its corresponding data object. The each() loop lets us pull the ID from that data and attach it to the bubble element.
内容的提问来源于stack exchange,提问作者HS__HS

