【问题标题】:For some reason, my D3 Map is displaying upside down - how can I flip it?出于某种原因,我的 D3 地图显示颠倒了 - 我该如何翻转它?
【发布时间】:2018-07-20 18:57:50
【问题描述】:

有一个我正在导入的 topoJSON 文件 - 看起来这应该很容易翻转,但我不知道。我应该在创建对象后转换对象还是调整 JSON?我尝试使用一些投影,这些投影翻转了对象,但整个地方都扭曲了。

<!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>

【问题讨论】:

    标签: javascript html d3.js svg topojson


    【解决方案1】:

    您没有使用投影 - 因此文件中的坐标无需转换即可转换为像素。如果您的数据具有典型的地理坐标或经纬度均为正数,则高值位于北端(大多数地图中的顶部),而低值位于南端(大多数地图中的底部)。

    在 svg 坐标中,低值位于顶部并随着向底部移动而增加 - 与大多数地理坐标约定相反。您可以使用 geoIdentity 作为投影来翻转 json 的 y 坐标:

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

    geojson 是您的功能集合:topojson.feature(us, us.objects.counties)

    然后在你的路径中使用它:

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

    【讨论】:

    • 这看起来应该可以工作,但由于某种原因,页面没有显示任何内容并且没有抛出任何错误。可能有一些我缺少的规模/位置吗?编辑:似乎 .reflectY(true) 导致我丢失了地图。
    • 我的错,你需要用这个修改翻译。 FitSize 将允许居中。没有错误和没有特征意味着特征通常被绘制在视野之外。我已经更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多