Search code examples
javascriptjqueryjqvmap

How does one dynamically set a color of a country through a var?


Anyone used http://github.com/manifestinteractive/jqvmap/ ?

These work:

$('#map').vectorMap('set', 'colors', { us: '#8EE5EE' });
$('#map').vectorMap('set', 'colors', { 'us': '#8EE5EE' });

But, this doesnt:

country_name = 'us';
$('#map').vectorMap('set', 'colors', { country_name: '#8EE5EE' });

Anyone know why?


Solution

  • Because that's not how object literals work. The key part in the key-value pair is interpreted as a literal string. You need to use bracket-syntax to have a dynamic key name. It's that or eval, and you don't want to use eval.

    var country_colors = {};
    var country_name = 'us';
    
    country_colors[country_name] = '#8EE5EE';
    
    $('#map').vectorMap('set', 'colors', country_colors);