I built a D3 map that highlights which counties voted for the new governor in my state. I want to build a similar map for another political race using the same code as my governor map. I copied the governor map code and modified it for the other race, changing the geojson file and where the svg will go. I put the other race's code into an external JS file and placed it below my governor JS file in my index.html. Now, depending which file is loaded first in my .html file, one map will appear while the other appears white. Is there anyway I can make both codes different enough to have the maps appear at the same time?
-
Are the files themselves exactly as you have posted on pastebin? Or is that code wrapped in another function? – NanoWizard Oct 25 '14 at 22:43
1 Answers
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.

- 1
- 1

- 2,104
- 1
- 21
- 34