2013-03-17 50 views
4

我的目標是使用d3爲給定的GeoJSON要素集合中的每個要素生成svg路徑。d3和小冊子之間的GeoJSON映射差異

當我使用傳單映射路徑時,所有功能看起來都很完美。

d3.json("ct_counties.geo.json", function(data) { 
    var leaflet_paths = leaflet_map.addLayer(new L.GeoJSON(data)); 
}); 

two maps

但是,當我使用映射D3的路徑,一些功能看上去是錯誤的。

d3.json("ct_counties.geo.json", function(collection) { 
    var bounds = d3.geo.bounds(collection); 

    var path = d3.geo.path().projection(project); 

    var feature = g.selectAll("path") 
     .data(collection.features) 
     .enter().append("path") 
     .attr('class','county'); 

    d3_map.on("viewreset", reset); 

    reset(); 

    function project(x) { 
     var point = d3_map.latLngToLayerPoint(new L.LatLng(x[1], x[0])); 
     return [point.x, point.y]; 
    } 

    function reset() { 
     var bottomLeft = project(bounds[0]); 
     var topRight = project(bounds[1]); 
     svg.attr("width", topRight[0] - bottomLeft[0]) 
     .attr("height", bottomLeft[1] - topRight[1]) 
     .style("margin-left", bottomLeft[0] + "px") 
     .style("margin-top", topRight[1] + "px"); 
     g.attr("transform", "translate(" + -bottomLeft[0] + "," + -topRight[1] + ")"); 
     feature.attr("d", path); 
    } 
}); 

查看地圖差異here。請參閱完整代碼here

由於兩張地圖都使用相同的特徵集合,爲什麼d3版本是錯誤的?

+2

貌似多邊形不同的解釋。由於點的順序可能。仔細檢查後,看起來每個多邊形都缺少一個點。可能是結尾粘在一起的那一點? – flup 2013-03-17 08:45:01

回答

22

D3沒有錯,數據不正確,Leaflet比較寬鬆。

以Litchfield的(左上郡)作爲一個例子:

{ 
    "type" : "Feature", 
    "properties" : { 
     "kind" : "county", 
     "name" : "Litchfield", 
     "state" : "CT" 
    }, 
    "geometry" : { 
     "type" : "MultiPolygon", 
     "coordinates" : [ [ [ [ -73.0535, 42.0390 ], [ -73.0097, 42.0390 ], 
       [ -73.0316, 41.9678 ], [ -72.8892, 41.9733 ], 
       [ -72.9385, 41.8966 ], [ -72.9495, 41.8090 ], 
       [ -73.0152, 41.7981 ], [ -72.9823, 41.6392 ], 
       [ -73.1631, 41.5571 ], [ -73.1576, 41.5133 ], 
       [ -73.3219, 41.5078 ], [ -73.3109, 41.4694 ], 
       [ -73.3876, 41.5133 ], [ -73.4424, 41.4914 ], 
       [ -73.4862, 41.6447 ], [ -73.5191, 41.6666 ], 
       [ -73.4862, 42.0500 ] ] ] ] 
    } 
} 

的多面不是封閉的,其端部不等於開始。 我繪製的座標,標誌着第一個座標紅色,最後一個綠色: points in the multipolygon

正如你可以看到,最後一個座標得到由D3丟棄。

GeoJSON specification

甲線性環是關閉LineString具有4個或更多個位置。第一個和最後一個位置是相同的(它們代表相同的點)。

那麼D3有一個點(沒有雙關語意)和應該的MultiPolygon通過添加在年底開始座標被關閉:

...[ -73.4862, 42.0500 ], [ -73.0535, 42.0390 ] ] ] ] 
+0

謝謝@flup。澄清一點:我並不是建議d3作爲框架是錯誤的;相反,我指的是我的d3地圖實現。 – s2t2 2013-03-18 03:55:48

+1

這個答案值得很多 – callum 2013-04-12 16:39:14