javascriptd3.jsdatamaps

How to dynamically change the color of a country on d3 map


var COLOR = 'blue';
var map = new Datamap({
  element: document.getElementById('map'),
  responsive: false,
});

function changeColor(countryCode) {
  map.updateChoropleth({
    countryCode: COLOR
  });
}

setInterval(function() {
  changeColor('USA');
}, 2000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datamaps/0.5.8/datamaps.world.min.js"></script>
<div id="map"></div>

I have the following javascript which renders a world map on HTML.

var map = new Datamap({
  element: document.getElementById('map'),
  responsive: true,
});

function changeColor(countryCode) {
  map.updateChoropleth({
    countryCode: 'blue'
  });
  console.log(countryCode + '--> colorChange');
}

setInterval(function() {
  changeColor('USA');
}, 2000);

I want to update the color of a particular country after a 2s. When I run the above code, the function changeColor is called after every 2s, but the function map.updateChoropleth does not seem to have any effect. In case, I change the following snippet:

function changeColor(countryCode) {
  map.updateChoropleth({
    countryCode: 'blue'
  });
  console.log(countryCode + '--> colorChange');
}

to

function changeColor(countryCode) {
  map.updateChoropleth({
    "USA": 'blue'
  });
  console.log(countryCode + '--> colorChange');
}

the function works as expected. Why does this not work?


Solution

  • The updateChoropleth function is looking for a property key literally named countryCode.

    A solution is populating an object and passing it to the function:

    var COLOR = 'blue';
    var map = new Datamap({
      element: document.getElementById('map'),
      responsive: false,
    });
    
    function changeColor(countryCode) {
      var obj = {};
      obj[countryCode] = COLOR;
      map.updateChoropleth(obj);
    }
    
    setInterval(function() {
      changeColor('USA');
    }, 2000);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/datamaps/0.5.8/datamaps.world.min.js"></script>
    <div id="map"></div>