javascript - 使用 d3 通过投影映射 geojson 分布数据

标签 javascript d3.js maps data-visualization geojson

我正在尝试使用 d3 绘制鸟类分布图。到目前为止,我已经成功使用 d3 绘制并投影了伊利诺伊州 map 的路径。现在,我从 eBird api 请求数据,然后将其读取为 geojson,然后创建一系列 d3 圆圈以根据 map 绘制它们。圆圈正在被创建并附加到 DOM,但我定义的投影似乎将它们绘制得太靠上和靠右。

仍在学习 d3 的基础知识,所以请耐心等待。我的代码可以在下面的要点中找到。

https://gist.github.com/cqlanus/599a6b02e5168a051fef948ba541e296

或者,如果我尝试将数据绘制为路径,则会创建路径元素,但它们不会出现在 DOM 上:

const sightings = svg.append('g').attr('class', 'sightings')

    sightings.selectAll('path')
      .data(sightingGeoArr)
      .enter().append('path')
      .attr('fill', '#000')
      .attr('d', geoPath)

最佳答案

Geojson 使用 x,y 格式作为坐标。然而你的 geojson 是 y,x:

    "coordinates": [result.lat, result.lng]

尝试:

    "coordinates": [result.lng, result.lat]

我没有你的状态geojson作为边界,但我估计了下面代码片段的合适投影,它显示了你的脚本的工作(我喜欢Ebird数据,但我没有考虑将其转换为geojson以便在d3之前,我得试一试)。

const height = 500, width = 500

/* Create a color function */

/* Define a projection function */
const albersProj = d3.geoAlbers()
  .center([0,40.08])
  .rotate([88.0,0])
  .translate([width/2,height/2])
  .scale(4000)

/* Define a path function */
const geoPath = d3.geoPath()
  .projection(albersProj)
  .pointRadius(5)

/* Attach svg to page */
var svg = d3.select( "body" )
  .append( "svg" )
  .attr( "width", width )
  .attr( "height", height );

/* Attach group to svg */
var g = svg.append( "g" );


/* Get iNaturalist data */
d3.json('http://ebird.org/ws1.1/data/obs/region_spp/recent?rtype=subnational1&r=US-IL&sci=Setophaga%20coronata&back=15&maxResults=500&locale=en_US&fmt=json&includeProvisional=true')
  .get((err, data) => {
    console.log(data.length)

    /* Manipulate it to be read as geojson */
    const sightingGeoArr = data.map(result => ({
      "geometry": {
        "type": "Point",
        "coordinates": [result.lng, result.lat]
      }
    }))

    const sightings = svg.append('g').attr('class', 'sightings')

    sightings.selectAll('circle')
      .data(sightingGeoArr)
      .enter().append('circle')
      .attr('fill', '#000')
      .attr('cx', d => albersProj(d.geometry.coordinates)[0])
      .attr('cy', d => albersProj(d.geometry.coordinates)[1])
      .attr('r', 2)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js"></script>

关于javascript - 使用 d3 通过投影映射 geojson 分布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43687281/

相关文章:

javascript - 从 Mapbox 绘制在这张 map 上的数据点的来源及其格式是什么?

Javascript自定义回调函数

javascript - 用户输入时自动更正单词

javascript - 如何在给定用户输入 X、Y 点的情况下绘制 HTML5 Canvas 线?

javascript - 我想将子文件夹页面内容与主文件夹中的页面链接

svg - 将任意数据附加到 D3.js 中的对象

javascript - 将节点添加到 d3 网络错误(使用 fiddle 示例)

javascript - 通过刷多路径图表无法绘制 d3.js Focus+Context

c++ - 如何避免将 const-ref 返回到缓存中的临时文件

iphone - iPhone 的缓存/离线 map ?