Skip to content

Instantly share code, notes, and snippets.

@mpmckenna8
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpmckenna8/b152a067884caacd02b4 to your computer and use it in GitHub Desktop.
Save mpmckenna8/b152a067884caacd02b4 to your computer and use it in GitHub Desktop.
d3 load data w/ datum()

This is a map of brazil in which I loaded all the cities w/ datum to show what happens when you do this. If you open the javascript console you'll see that there's a giant object returned instead of each individual point like you may want. To do this use data() and enter i think. Hopefully another example soon will show how to do that. But i think it's faster to load the data this way but you can't add classes to each thing based on it's properties like you might want all the cities outside of brazil a different color.

Also I think I could have rotated brazil to the middle of the map rather than rotating stuff but whatever. I think I looks alright as is. I do want to look more into how to properly set up projections for different zoom levels though....

<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg{
background:#2379d5;
}
/* CSS goes here. */
.coun { fill: #27ae60;
opacity:.6;
stroke:black;
stroke-width:.8; }
.grat{
stroke:grey;
stroke-width:1px
}
.city{
fill:#fad959;
}
.city:hover{
fill:blue
}
</style>
<body>
<script src="http://d3js.org/d3.v3.js"></script>
<script src="http://d3js.org/topojson.v1.js"></script>
<script>
var height = 475;
var width = 600;
var projection = d3.geo.albers()
.center([-54,-8.4])
.parallels( [11.5,-38])
.scale(550)
//rotating is long lat and around the origin
.rotate([55,-5,-5])
.translate([width/2 - 450,height/2 -40])
var graticule = d3.geo.graticule();
var svg = d3.select('body').append('svg').attr('width', width).attr('height', height);
var path = d3.geo.path()
.projection(projection);
svg.append('path')
.datum(graticule)
.attr('class', "grat")
.attr('d',path)
.attr('fill','none')
d3.json('/mpmckenna8/raw/b018c6bf85e272495522/brazilWor.json', function(err, world){
if(err){console.log(err)}
svg.append('path')
.datum(topojson.feature(world,world.objects.countries110))
.attr('d',path)
.attr('class',function(d){
console.log(d);
return 'coun'});
var citi = topojson.feature(world,world.objects.brazilCit)
//console.log(citi.features[2].geometry)
//adding stuff all at once w/ datum like w/ graticule everthing it going to be the same.
// So the anonymous function in .attr('class',funct) is worthless more or less because it's all just one big thing.
svg.append('path')
.datum(citi)
.attr('d',path)
.attr('class',function(d,i){
console.log(d);
return 'city'
})
d3.selectAll('.city')
.on('click', function(d,i){
console.log(i);
})
})
console.log(projection([-54,-8.4]))
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment