markmarkoh / datamaps

Customizable SVG map visualizations for the web in a single Javascript file using D3.js
http://datamaps.github.io
MIT License
3.78k stars 1.01k forks source link

Unable to update choropleth with object #209

Closed lopezavila85 closed 9 years ago

lopezavila85 commented 9 years ago

Hello everyone,

I am loading a Datamap with JSON objects similar to this one:

"ARG": {
    "country":"Argentina",
    "inetUsers":"59,9"
  }

Furthermore, when I load it using d3.json method I assign the fillKey:

d3.json("myFile.json", function(error, data) {    
    for (var key in data) {
      if (data.hasOwnProperty(key)) {       
        data[key].inetUsers = parseFloat(data[key].inetUsers.replace(',', '.'));
        data[key].fillKey = getFillKey(data[key].inetUsers);
        data[key].selectedCountry = false;
      }
    }

//mapData is a global variable to contain the map data to process it afterwards
    mapData = data;    
    map.updateChoropleth(mapData);
  });

I want to select a country and mark it with a different color:

    done: function(dm) {
      dm.svg.selectAll('.datamaps-subunit').on('click', function(geography) {

        var m = {};

        if (mapData) {
          for (var key in mapData) {
            // this will check if key is owned by data object and not by any of it's ancestors
            if (mapData.hasOwnProperty(key) && key == geography.id) {

              if (mapData[key].selectedCountry) {
                mapData[key].selectedCountry = false;
                mapData[key].fillKey = getFillKey(mapData[key].inetUsers);
              } else {
                //The country is selected
                mapData[key].selectedCountry = true;
                mapData[key].fillKey = '#E8E8E8';
              }

//THE UPDATE IN THE GLOBAL VARIABLE IS OK, BUT I JUST WANT TO UPDATE ONE COUNTRY, THE CLICKED ONE
//This line does not work
              m[key] = mapData[key];

//This line DO work.
  m[key] =  '#E8E8E8';
              break;
            }
          }

          if (!jQuery.isEmptyObject(m)) {
            console.log(m);
            //Can't I update the map this way???
            dm.updateChoropleth(m);
          }
        }
        //
      });
    }

Why can't I update the map with the full object? Or how it should be done? Thanks in advance

lopezavila85 commented 9 years ago

It seemed to be possible. However, the object had to be created in a slightly different way:

  var m = {};
  m[key] = {
    inetUsers: mapData[key].inetUsers,
    fillKey: mapData[key].fillKey,
    country: mapData[key].country,
    selectedCountry: mapData[key].selectedCountry
  };

  map.updateChoropleth(m);