D3.js 如何在d3中显示featureCollection的属性(使用鼠标)

D3.js 如何在d3中显示featureCollection的属性(使用鼠标),d3.js,D3.js,在用D3显示我的地图后,我需要在上面放置客户位置。这样做没有问题,但当用户单击“我的客户位置”时,我需要显示有关properties成员中当前保存的位置的数据。现在,当我对所选客户位置执行console.log()操作时,我将获得整个功能数据,而不是用户选择的单个功能数据。这是我的客户位置数据: var customerListData = { "type":"FeatureCollection", "features":[ { "geometry":{"

在用D3显示我的地图后,我需要在上面放置客户位置。这样做没有问题,但当用户单击“我的客户位置”时,我需要显示有关properties成员中当前保存的位置的数据。现在,当我对所选客户位置执行console.log()操作时,我将获得整个功能数据,而不是用户选择的单个功能数据。这是我的客户位置数据:

var customerListData =
{
    "type":"FeatureCollection",
    "features":[
    {
        "geometry":{"type": "Point", "coordinates": [-77.4918710, 38.1991360]},
        "properties": {"NUM":0,"NAME":"DFA54635","formattedAddress":"4503 Cornwall     Court, Fredericksburg, VA 22408, USA"}
    },
    {
        "geometry":{"type": "Point", "coordinates": [-81.0974798, 36.9448153]},
        "properties": {"NUM":1,"NAME":"DFA54644","formattedAddress":"475 North 22nd Street, Wytheville, VA 24382, USA"}
    }
   ...
下面是我如何显示这些数据的

// paint the customer locations
svg.selectAll(".cities").data([customerListData])
    .enter().append("path")
.attr("class","cities")
.attr("d", path)
.on("click", function(d) 
     {
   console.log(d);
     }) 
.append("title").text(function(d) 
{ 
    console.log(d);
});
在上述两种情况下,控制台日志都会显示整个功能集合:

Object { type="FeatureCollection", features=[105]}

那么…如何使用鼠标作为输入来获得准确的特征呢?

您的路径可能是用投影定义的geo.path。如果要显示每个单独的点并访问绑定到每个点的数据,则需要不使用geo.path将其追加,而是将其单独放置并单独访问投影:

 d3.select("svg").selectAll("circle.cities").data(customerListData.features)
 .enter()
 .append("circle")
 .attr("r", 5)
 .attr("cx", function(d) {return projection([d.geometry.coordinates])[0]})
 .attr("cy", function(d) {return projection([d.geometry.coordinates])[1]})
 .on("click", function(d) {console.log(d)})
这是假设您的投影变量名为“projection”。它是一个接受两值数组并返回两值投影数组的函数,第一个值[0]是x坐标,第二个值[1]是y坐标


可能有一种方法可以使用geo.path访问每个点,但我不知道。

您是否尝试过
.data(customerListData.features)
?是的。如果我尝试使用(svg.selectAll(“.cities”).data(customerListData.features))显示数据,则不会显示任何内容。但是,console.log()被多次调用,并显示以下内容:对象{geometry={…},属性{…}我是否需要一次显示一个点的数据,而不是一次显示整个集合?看起来这可能有效,但这似乎是一个缓慢的过程。是的,你需要一次画一个。这不会减慢绘图速度。我实际上没有用上面的代码解决我的问题,但它(上面的代码)与我的解决方案非常接近,因此这是正确的方法。一如既往,谢谢你的帮助。