使用D3.js绘制城市行政区GeoJSON多边形仅显示空白矩形求助
D3.js绘制行政区地图仅显示米色矩形的问题排查与解决
问题场景
尝试用D3.js绘制莱比锡行政区多边形地图,但页面仅显示一个米色矩形,控制台无报错,数据输出看似正常。相关代码及GeoJSON结构如下:
页面代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Lpgz crime rates</title> <script src="https://d3js.org/d3.v6.min.js"></script> <style> #map { width: 800px; height: 600px; border: 1px solid black; } .map path { stroke: #999; stroke-width: 0.5; } </style> </head> <body> <svg id="map" viewBox="0 0 800 600"></svg> <script> const width = 800; const height = 600; const margin = 20; const svg = d3.select('#map') .attr('width', width) .attr('height', height); Promise.all([ d3.json('data/Leipzig_ortsteile.geojson'), d3.json('data/crime_rates.json') ]).then(([ortsteile, crimeRates]) => { console.log("GeoJSON data:", ortsteile.features); console.log("Crime rates data:", crimeRates); const projection = d3.geoMercator() .fitSize([width, height], ortsteile); const pathGenerator = d3.geoPath().projection(projection); const colorScale = d3.scaleSequential(d3.interpolateReds) .domain([0, d3.max(Object.values(crimeRates))]); const paths = svg.selectAll('path') .data(ortsteile.features) .enter() .append('path') .attr('d', d => { const pathData = pathGenerator(d); console.log(`Path data for ${d.properties.Name}:`, pathData); return pathData; }) .attr('fill', d => { const rate = crimeRates[d.properties.Name]; console.log(`Area: ${d.properties.Name}, Crime rate: ${rate}`); return rate ? colorScale(rate) : '#ccc'; }) .attr('stroke', '#999') .attr('stroke-width', '0.5'); console.log("SVG Paths:", paths); }).catch(err => console.error("Error loading data:", err)); </script> </body> </html>
GeoJSON结构片段
{ "type": "FeatureCollection", "name": "log_lat", "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "features": [ { "type": "Feature", "properties": { "FID": 0, "OT": "00", "Name": "Zentrum" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 12.37927526130802, 51.344360566287889 ], [ 12.379117566590359, 51.344399728002436 ], [ 12.378953533569369, 51. ....
排查与解决步骤
1. 优先排查数据匹配问题
从代码看,填充色默认值为#ccc(米色),如果所有行政区的crimeRates[d.properties.Name]返回undefined,所有区域会叠加成一个米色矩形。
- 检查控制台输出的
Area: ${d.properties.Name}, Crime rate: ${rate},确认rate是否为undefined - 核对
crime_rates.json的键名与GeoJSON中d.properties.Name的拼写、大小写、空格是否完全一致,比如是否存在"Zentrum"和"zentrum"的大小写差异 - 临时修改填充色为分类色,验证区域是否能正常渲染:
.attr('fill', (d,i) => d3.schemeCategory10[i%10])
2. 修正投影适配逻辑
fitSize会将地图完全适配到指定尺寸,但如果SVG同时设置了viewBox和width/height,可能导致坐标冲突。建议改用fitExtent预留边距,避免边缘裁切:
const projection = d3.geoMercator() .fitExtent([[margin, margin], [width - margin, height - margin]], ortsteile);
3. 检查GeoJSON有效性
- 确认Polygon坐标是否闭合:每个多边形的最后一组坐标必须与第一组完全相同,否则路径无法正常闭合
- 验证GeoJSON格式是否符合标准,可通过在线GeoJSON校验工具检查(本地校验,无需外链)
4. 修复样式选择器冲突
CSS中.map path选择器与SVG的id="map"不匹配,改为#map path确保样式生效:
#map path { stroke: #999; stroke-width: 0.5; }
内容的提问来源于stack exchange,提问作者Anastasiia Iurshina
相关产品推荐
相关产品推荐

