2015-02-10 23 views
0

我想創建一個地圖並繪製一些使用D3的點,我發現了一些很好的例子,但我相信我被卡住了。我的猜測是,我沒有正確處理繪圖點,根據我如何獲得數據結構。我可以使用一些幫助 - 這是我的第一次嘗試。這是我到目前爲止有:D3,繪製地圖,可能的數據格式

var m_width = document.getElementById("map").offsetWidth, 
width = 938, 
height = 500; 

var projection = d3.geo.mercator() 
.scale(150) 
.translate([width/2, height/1.5]); 

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

var svg = d3.select("#map").append("svg") 
.attr("preserveAspectRatio", "xMidYMid") 
.attr("viewBox", "0 0 " + width + " " + height) 
.attr("width", m_width) 
.attr("height", m_width * height/width); 

svg.append("rect") 
.attr("class", "background") 
.attr("width", width) 
.attr("height", height) 


var g = svg.append("g"); 

d3.json("scripts/world-110m2.json", function(error, us) { 
g.append("g") 
.attr("id", "countries") 
.selectAll("path") 
.data(topojson.feature(us, us.objects.countries).features) 
.enter() 
.append("path") 
.attr("id", function(d) { return d.id; }) 
.attr("d", path) 

}); 

svg.selectAll(".pin") 
.data(places) 
.enter().append("circle", ".pin") 
.attr("r", 5) 
.attr("transform", function(d) { 
return "translate(" + projection([ 
    d.earthquakes.lon, 
    d.earthquakes.lat 
]) + ")" 
}); 

window.addEventListener('resize', function(event){ 
var w = document.getElementById("map").offsetWidth; 
svg.attr("width", w); 
svg.attr("height", w * height/width); 
    }); 

與「地方」的數據結構像這樣

var places = {"count":"392","earthquakes":[{"src":"us","eqid":"2010sdbk","timedate":"2010-01-31 15:18:44","lat":"-18.7507","lon":"169.3940","magnitude":"5.1","depth":"231.50","region":"Vanuatu"} 

,所有的地方都在裏面裏面的地方對象數組「地震」。 (特別是裏面和拉特)。

世界地圖顯示正常,我只是無法得到這些陰謀點工作。將非常感謝任何幫助。謝謝閱讀!!

回答

1

你幾乎擁有它,但幾個問題在這裏:

1)傳遞給.data的數據應該是一個數組(在哪裏添加你的社交圈)。

2.)在您的places對象中,緯度/經度是字符串,需要轉換爲數字。

嘗試:

var places = { 
    "count": "392", 
    "earthquakes": [{ 
    "src": "us", 
    "eqid": "2010sdbk", 
    "timedate": "2010-01-31 15:18:44", 
    "lat": "-18.7507", 
    "lon": "169.3940", 
    "magnitude": "5.1", 
    "depth": "231.50", 
    "region": "Vanuatu" 
    }] 
}; 

svg.selectAll(".pin") 
    .data(places.earthquakes) //<-- pass array 
    .enter() 
    .append("circle") 
    .attr("class","pin") 
    .attr("r", 5) 
    .attr("transform", function(d) { 
    return "translate(" + projection([ 
     +d.lon, //<-- coerce to number 
     +d.lat 
    ]) + ")"; 
    }); 

here