d3.js渲染首尔分级统计图时仅显示黑色矩形而非地图如何解决?
问题原因及修复方案
- 投影中心点配置错误:你当前设置的中心点
[128, 36]是韩国中部偏东的海域位置,并非首尔的实际坐标,首尔核心区经纬度约为[126.98, 37.56],中心点偏移导致投影渲染的区域根本不是首尔市域,自然只会显示空白/黑色色块。 - 缩放参数适配问题:旧版D3没有
fitSize的情况下,你当前设置的scale=5000缩放值太小,相当于把视角拉得极高,首尔在图上只有极小的一个点,自然显示异常,市级地图的墨卡托投影缩放值一般要调到70000-90000区间才能正常显示首尔市域范围。 - 路径样式缺省:你没有给path设置显式的填充、描边样式,默认填充为黑色,如果边界刚好切到渲染区域也会出现全黑矩形的情况。
修改后可运行的参考代码
var width = 600, height = 700; var svg = d3.select('#chart').append('svg') .attr('width',width) .attr('height',height); // 修正中心点为首尔实际坐标,调整缩放值 var projection = d3.geo.mercator() .center([126.98, 37.56]) .scale(80000) // 可以根据你的JSON坐标精度上下浮动10000调整 .translate([width/2, height/2]); var path = d3.geo.path() .projection(projection); d3.json('Seoulmap.json',function(error,data) { if (error) throw error; // 增加错误捕获避免JSON加载失败无提示 var features = topojson.feature(data, data.objects['Seoulmap']).features; svg.selectAll('path') .data(features) .enter().append('path') .attr('class','name') .attr('d',path) .attr('id',function(d) { return d.properties.ADM_DR_NM; }) // 增加显式样式 .style('fill', '#f0f0f0') .style('stroke', '#999') .style('stroke-width', 0.5); });
旧版D3自动适配视图的方案
如果不想手动调整缩放和中心点,可以在JSON回调中加入以下代码,通过计算要素边界自动适配画布:
var geoFeature = topojson.feature(data, data.objects['Seoulmap']); var bounds = d3.geo.bounds(geoFeature), dx = bounds[1][0] - bounds[0][0], dy = bounds[1][1] - bounds[0][1], x = (bounds[0][0] + bounds[1][0]) / 2, y = (bounds[0][1] + bounds[1][1]) / 2, scale = 0.9 / Math.max(dx / width, dy / height), translate = [width / 2 - scale * x, height / 2 - scale * y]; // 直接覆盖之前的投影配置 projection.scale(scale).translate(translate);
内容的提问来源于stack exchange,提问作者Johan
相关产品推荐
相关产品推荐

