Jan Seipel
Jan Seipel

Reputation: 119

d3js gives typeError "d is undefined"

I built a d3 map and have to access the bound data for various actions. When I do this with .on("mouseover",...) or .on("mousemove",...), it works fine. But I want to set the fill color based on these values, too. When I try to do this by .attr("fill",...) and a callback function, it gives me a typeError "d is undefinded". Here is a working and a non-working code-example:

kommunen
    .selectAll("path")
    .data(featuresKommunen)
    .enter().append("path")
    .attr("d", path)
    .attr("class", "kommune")
    .on("mouseover",function (d){ 

        // gives me the correct values
        console.log(d.properties.AGS) 

    })

non-working:

kommunen
    .selectAll("path")
    .data(featuresKommunen)
    .enter().append("path")
    .attr("d", path)
    .attr("class", "kommune")
    .attr("fill",function (d){ 

        // gives me TypeError: d is undefined
        console.log(d.properties.AGS)

        // the same here
        console.log(d.properties)

    })

Logging the root element instead works again

kommunen
    .selectAll("path")
    .data(featuresKommunen)
    .enter().append("path")
    .attr("d", path)
    .attr("class", "kommune")
    .attr("fill",function (d){ 

        console.log(d)
        // works and gives me a list of objects:
        // Object { type: "Feature", properties: Object, geometry: Object }
        // Object { type: "Feature", properties: Object, geometry: Object }
        // Object { type: "Feature", properties: Object, geometry: Object }
        // ...

    })

Upvotes: 2

Views: 3395

Answers (1)

Jan Seipel
Jan Seipel

Reputation: 119

My geojson produced some objects without properties and coordinates (wherever they came from...) so that they were not visible on the screen but exited in the DOM. After I wrote a small statement to check if properites are defined, it worked!

kommunen
.selectAll("path")
.data(featuresKommunen)
.enter().append("path")
.attr("d", path)
.attr("class", "kommune")
.attr("fill",function (d){

   // works by skipping the missing properies-values
   if (d.properties) {console.log(d.properties.AGS)}

})

Upvotes: 2

Related Questions