score:0

It appears you are writing to the global namespace (In your case, the window object).

When you make the json request through d3, the json file is loaded asynchronously, which means the rest of your javascript code will keep running. This also means that whichever file is being loaded second is overriding all of the variables you just declared, and by the time the json request is processed, the variables (that were declared by the first script) were already overridden by the second script, so each time the json is loaded, you're essentially writing to the same DOM element.

If you want a quick fix, you could just wrap each script in a function and call them onload or use DOMContentLoaded or jquery, but since they are so similar you could just use a single function such as:

function createPoliticalMap(elementID, jsonUrl){
    // your code...
    //...
    var svg = d3.select(elementID).append("svg")
    //...   
    d3.json(jsonUrl,function(error,geodata) {
        //...
    }
}

And then just do:

createPoliticalMap('#map-gov', 'data/gov.geojson');
createPoliticalMap('#map-ag', 'data/ag.geojson');

Or you could take advantage of JavaScript's object oriented capabilities to define a 'class' of sorts like:

function PoliticalMap(elementID, jsonUrl){
    // define your stuff and make the json request based off of the parameters.
}

And do:

var govMap = new PoliticalMap('#map-gov', 'data/gov.geojson');
var agMap = new PoliticalMap('#map-ag', 'data/ag.geojson');

If you wanted to be able to manipulate the D3 graph after creation.

Then adding more political maps becomes trivial, and you could include the code more easily in other pages if you want.


Related Query