Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

javascript - For some reason, my D3 Map is displaying upside down - how can I flip it?

Have a topoJSON file that I am importing - seems like this should be easy to flip, but I have no idea. Should I be transforming the object after it's created or adjusting the JSON? I tried using some projections, which flipped the object, but distorted it all over the place.

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.counties {
  fill: blue;
}

.states {
  fill: none;
  stroke: #fff;
  stroke-linejoin: round;
}

</style>
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script>


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

var path = d3.geoPath()

 //first make projection  
  //var projection = d3.geoMercator();
  //var path = d3.geoPath()
  //  .projection(projection);



d3.json("data.topojson", function(error, us) {
  if (error) throw error;


 var counties = topojson.feature(us, us.objects.counties),
                    counties = counties.features.filter(function(d) { return d.properties.AWATER === 0; });

  svg.append("g")
      .attr("class", "counties")
    .selectAll("path")
      .data(counties)
    .enter().append("path")
      .attr("d", path)
      .style("fill", 'blue')
      .append('g')
      attr('transform', 'rotate(180 0 0)');
});

</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You aren't using a projection - so the coordinates in the file are translated to pixels with no transformation. If your data has typical geographic coordinates, or lat longs that are both positive, high values are at the north end (the top in most maps), and low values are at the south end (the bottom in most maps).

In svg coordinates, low values are located at the top and increase as one moves towards the bottom - the opposite of most geographic coordinate conventions. You could use a geoIdentity as your projection to flip the json's y coordinates:

var projection = d3.geoIdentity()
  .reflectY(true)
  .fitSize([width,height],geojson)

Where geojson is your feature collection: topojson.feature(us, us.objects.counties)

And then use it with your path:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...