我正在尝试使用 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/