Search code examples
javascriptjsond3.jsdatamaps

Load popup on hover data from json file for datamaps


The datamaps "Getting started" page has a section on customizing the text when a user hovers over a specific country. However, they do so by hard-coding that info:

<script>
    var map = new Datamap({
        element: document.getElementById('container'),
        fills: {
            HIGH: '#afafaf',
            LOW: '#123456',
            MEDIUM: 'blue',
            UNKNOWN: 'rgb(0,0,0)',
            defaultFill: 'green'
        },
        data: {
            IRL: {
                fillKey: 'LOW',
                numberOfThings: 2002
            },
            USA: {
                fillKey: 'MEDIUM',
                numberOfThings: 10381
            }
        },
        geographyConfig: {
            popupTemplate: function(geo, data) {
                return ['<div class="hoverinfo"><strong>',
                        'Number of things in ' + geo.properties.name,
                        ': ' + data.numberOfThings,
                        '</strong></div>'].join('');
            }
        }
    });
</script>

I would like to load that info from an external .json file so that I can update it easily. How can I do this? I've tried setting dataURL, but that expects a complete topojson file, which I don't need to update. Any help greatly appreciated!


Solution

  • dataUrl at the root level can take a json or csv file, like this example here: http://bl.ocks.org/markmarkoh/11331459

          var election = new Datamap({
            scope: 'usa',
            element: document.getElementById('container1'),
            geographyConfig: {
              popupTemplate: function(geo, data) {
                return data && data.info && "<div class='hoverinfo'><strong>" + data.info + "</strong></div>";
              },
              highlightOnHover: false,
              borderColor: '#444',
              borderWidth: 0.5
            },
            dataUrl: 'data.json',
            dataType: 'json',
            data: {},
            fills: {
              'Visited': '#306596',
              'neato': '#0fa0fa',
              'Trouble': '#bada55',
              defaultFill: '#dddddd'
            }
          });
    

    While the resource at data.json looks like:

    {
      "NY": {"fillKey": "Visited", "anotherProperty": "Born here"},
      "TX": {"fillKey": "Visited", "anotherProperty": "Live here"},
      "CA": {"fillKey": "Visited", "anotherProperty": "Here while writing this code"}
    }