Andrew
Andrew

Reputation: 6860

Style fill for d3.js topojson map not completely filling

I am trying to add a color to a topojson map. When I added the fill, I got a very odd output where some of the color was changed but random swathes of it were left the same as before. The gray image is the one before I added the fill. I want the second map to be entirely orange.

without fill

with fill

Code is as follows:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
  stroke: white;
  stroke-width: 0.25px;
  fill: grey;
}

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script>
var width = 1200,
    height = 1200;

var projection = d3.geo.mercator()
    .center([0, 5 ])
    .scale(200)
    .rotate([-180,0]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var path = d3.geo.path()
    .projection(projection);

var g = svg.append("g");


// load and display the World
d3.json("us_states.json", function(error, us) {
  g.append("g")
      .attr("id", "states")
    .selectAll("path")
      .data(topojson.feature(us, us.objects.states).features)
    .enter().append("path")
      .attr("d", path)
      .style("fill", "#ffc04c"); //this is the offending line

  g.append("path")
      .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
      .attr("id", "state-borders")
      .attr("d", path);

});
var zoom = d3.behavior.zoom()
    .on("zoom",function() {
        g.attr("transform","translate("+ 
            d3.event.translate.join(",")+")scale("+d3.event.scale+")");
        g.selectAll("circle")
            .attr("d", path.projection(projection));
        g.selectAll("path")  
            .attr("d", path.projection(projection)); 

  });
svg.call(zoom)

</script>
</body>
</html>

Upvotes: 0

Views: 1116

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

The problem isn't actually in the paths for the states themselves (the line you highlighted), but in the state borders that you're appending afterwards -- those are filled grey according to your CSS and that's what you're seeing.

To fix, set fill: none for paths in CSS.

Upvotes: 4

Related Questions