我从OSM下载了一个文件并采用了几个坐标来练习从GeoJSON加载数据并将它们写入SVG。大多数JS代码都来自D3Vienno的地图教程,但即使我没有得到错误,我也无法在屏幕上显示任何内容。这是JS文件:
window.onload = function(){
var canvas = d3.selectAll("body").append("svg")
.attr("width", 600)
.attr("height", 600)
d3.json("test.geojson", function (data){
var group = canvas.selectAll("g")
.data(data)
.enter()
.append("g")
var projection= d3.geo.albers();
var path = d3.geo.path().projection(projection); //.scale(450).translate([0, 1980]);
var areas = group.append("path")
.attr("d", path)
.attr("class", "area")
.style("stroke-width", 1)
.style("fill", "none")
.style("stroke", "steelblue");
});
}
GeoJSON文件已经过jsonformatter验证,我还构建了一个JSFiddle来查看是否会产生影响。
如果我没有注释掉.scale(450).translate([0, 1980])
部分,我会得到一个“不是函数错误”,但它在API中,我相信它的格式正确。
这也是HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="http://localhost:8080/d3.min.js"></script>
<!--<script src="test.geojson"></script>-->
<script type="text/javascript" src="mapPractice.js"></script>
</head>
<body>
</body>
</html>
如果我没有注释掉GeoJSON的脚本标记,我会收到“意外令牌错误:在GeoJSON文件中,这种情况一直持续到我删除除坐标之外的所有内容,然后我得到”无法读取属性的长度D3文件中的'of null'。对于这样一个多部分的问题我很抱歉,但我已经尝试了解这个问题好几天了,我只是进入了圈子。
答案 0 :(得分:1)
d3.json()可能有点难以理解。埋在the explanation中,你会看到:
使用两个参数调用回调:错误(如果有)和解析的JSON
所以,你可以试试
d3.json("test.geojson", function (error, data) {
回调的第一个参数是错误(如果你的json文件被正确读取,它将为null或未定义)。
答案 1 :(得分:0)
.scale()
和.translate()
都是d3.geo.projection
的方法,而不是d3.geo.path()
的方法。你可能想要这样的东西:
var projection= d3.geo.albers()
.scale(450).translate([0, 1980]); // Call .scale() and .translate() on the projection!
var path = d3.geo.path().projection(projection);
此外,在您的JSFiddle中,您将绑定您的数据:
var group = canvas.selectAll("g")
.data(data.coordinates)
因为这只会绑定坐标数组,所以没有输入需要GeoJSON的地理路径生成器。对于要呈现的LineString
,您需要绑定为:
var group = canvas.selectAll("g")
.data([data])
检查SVG的源代码,你可以看到,这实际上插入了路径,虽然它不会被渲染,因为它是小而不在屏幕上。 This应该为您提供一个良好的起点,从优化比例和翻译的位置,以您需要的方式呈现它。