javascript - 使用 d3 渲染 geoJSON

标签 javascript json d3.js geojson topojson

我有一个 geoJSON 文件,我正在尝试使用 d3 进行渲染,但在定位正确的投影功能时遇到了困难。

目前,我一直在使用在许多 d3 示例中找到的 us.json 文件,但我目前正在处理的 map 使用美国“通勤区”(CZ) 而不是土地、州、或县。

习惯了打电话

topojson.feature(us, us.objects.states)

显示正确的层但是我的文件没有组织成对象并且没有多个层。这是我尝试使用的 geoJSON 文件的摘录:

{"type":"FeatureCollection","bbox":[-120.30602148510043,6.667736880597216,-70.95829310710806,34.46308750538215],"features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-83.802805983004,22.64602264051764],[-83.8080569412408,22.638128812605782],

这是我渲染失败的代码:

d3.json("CZ90.zip.geojson", function(error, us) {
    if (error) throw error;

    d3.select("svg").append("path")
        .datum(topojson.feature(us, us.CZ90))
        .attr("d", d3.geo.path());
});

由于没有对象,我省略了“.object”,当我将文件放入 Mapshaper 时,它正确地呈现了一个名为“CZ90”的层,这就是我写“us.CZ90”而不是“我们.objects.states”

我意识到我正在调用“topojson.feature”而不是特定于 geoJSON 的东西,但我也无法在不丢失投影类型/信息的情况下成功地将文件转换为 Mapshaper 中的 topoJSON。

在 .datum 调用中以该层为目标的正确方法是什么?

如果我能找到像 us.json 这样包含通勤区层的 topoJSON 文件,整个问题也将得到解决!

最佳答案

最终从我的开发人员 friend 那里得到了一些帮助,答案比我的问题简单得多。

似乎 d3.json() 本身就适合读取我的 geoJSON 文件的结构,而无需使用 datum() 所需要的只是调用:

d3.json("CZ90.zip.geojson", function(error, geoData) {
    d3.select("svg").append("path")
        .attr("d", path(geoData));
}

注意:这里使用的是d3.v4

这是能够成功渲染 map 的完整脚本:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
    path {
      fill: #ccc;
      stroke: #fff;
      stroke-linejoin: round;
    }
</style>

<svg width="960" height="500"></svg>
<script src="//d3js.org/d3.v4.min.js"></script>

<script>

var width = 960;
var height = 620;

var chosenProjection = d3.geoMercator()
  .scale(600)
  .translate([1300, 450])

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

d3.json("CZ90.zip.geojson", function(error, geoData) {

  d3.select("svg").append("path")
      .attr("d", path(geoData));
});

</script>

希望这能帮助其他陷入如此简单障碍的人!

关于javascript - 使用 d3 渲染 geoJSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42906648/

相关文章:

asp.net - 从 asp.net mvc Controller 操作获取查询字符串的值 &lt;script type ="text/javascript">

android - 创建嵌套的 JSON 对象

javascript - Uncaught ReferenceError : d3 is not defined

asp.net-mvc - MVC 6 中 @Scripts.Render 的替代品是什么

javascript - 尝试使用 phantomjs 和 Selenium 运行单元测试时出错

javascript - jQuery 幻灯片放映更新 url 与哈希值

javascript - 从服务器读取文本文件(Json)并发送给客户端(Javascript)

arrays - 具有多个数组的 PowerShell ConvertTo-JSON

javascript - 如何在 MAMP 本地服务器中运行 d3 Javascript

javascript - div淡入时改变背景颜色