Open chrismp opened 8 years ago
hey @chrismp I did a quick try on this one:
var fills = {
someOtherFill: '#ff0000',
defaultFill: '#00ff00'
};
var map = new Datamap({
element: document.getElementById('container'),
scope: 'usa',
fills: fills,
geographyConfig: {
highlightOnHover: false,
},
data: {
IL: {
fillKey: 'someOtherFill'
}
},
done: function(datamap) {
datamap.svg.selectAll('.datamaps-subunit').on('click', function(geography) {
var state_id = geography.id;
var fillkey_obj = datamap.options.data[state_id] || {fillKey: 'defaultFill'};
var fillkey = fillkey_obj.fillKey;;
var fillkeys = Object.keys(fills);
var antikey = fillkeys[Math.abs(fillkeys.indexOf(fillkey) - 1)];
var new_fills = {
[geography.id] : {
fillKey: antikey
}
};
datamap.updateChoropleth(new_fills);
});
}
});
try it out here http://bl.ocks.org/briwa/60024d70a5aee921d5910828fe8115be
this works when you only have two colors and you're toggling between those two (like your example). this is a really simple implementation but i hope you get the idea. hope this helps! cheers! 🍺
p.s: i'm turning off highlightOnHover
because it messes with the color
Inside the onclick, you need to check if any other country is already highlighted . If it is, you need to follow two steps, discolor previous country and color the new country. If no other country is already coloured, just go ahead and color the new country but save the geog id so that it can be used when the next country is clicked. ``
var previous_geography=0; datamap.svg.selectAll('.datamaps-subunit').on('click', function(geography) {
if ( previous_geography !=0)
{
now_geography=geography.id
console.log("Previous geography was clicked, we need to delete the previous color first")
geography.id=previous_geography
update_color(geography.id);
update_color(now_geography);
}
else {
update_color(geography.id);
}
function update_color(id)
{
console.log("id recieved is"+ id);
geography.id = id;
var state_id = geography.id;
previous_geography=geography.id;
var fillkey_obj = datamap.options.data[state_id] || {fillKey: 'defaultFill'};
var fillkey = fillkey_obj.fillKey;;
var fillkeys = Object.keys(fills);
var antikey = fillkeys[Math.abs(fillkeys.indexOf(fillkey) - 1)];
var new_fills = {
[geography.id] : {
fillKey: antikey
}
};
console.log (new_fills);
datamap.updateChoropleth(new_fills);
}
});
``
Here's what my code looks like:
When the map loads, all states are colored with the
defaultFill
color. But when I click each state, I want it to toggle betweeldefaultFill
and"SomeOtherFill"
colors.I'm not sure how to do this with the
done:
callback part of themap
object.What must I do to toggle each state's color on click?