简体   繁体   中英

d3 extracting values from selection after filtering data on mouseover

I apologize for the strange title, it wasn't easy to describe my problem, hopefully others in need of a solution to the same problem end up here. I have some markers on a map; their x,y position is produced by long, lat provided by some devices ips, so some markers overlap because they have the exact x,y values. I am trying to create a tooltip that on hover, will show all the overlapping markers' name. Here is where I am so far.

Sample dataset:

dataset= [
{long: -75, lat: 43, name: 'name1'},
{long: -75, lat: 43, name: 'name2'}
]

tooltip=d3.select('body').append('div')

markers=d3.selecltAll('.marker').data(dataset).enter().append()
  .attr('class', 'marker')
  .on('mousemove', (d)-> 
    myv=[]
    vals=projection([d.long, d.lat])
    d3.selectAll('.marker').filter((d,i) ->
      proj = projection([d.long, d.lat])
      proj[0] < (vals[0]+5) && proj[0] > (vals[0]-5) && proj[1] < (vals[1]+5) && proj[1] > (vals[1]-5) 
    ).text (d) ->
      myv.push(d.name)
  )

So here are my questions,

1) Using the text function to push the d.name in the myv dataset, works, but doesn't feel right. I've been trying for the past couple of hours to push this in a cleaner way, but couldn't do it. I tried using datum (d) -> myv.push(d.name) that only works ONCE for some reason only on the first hover.

2) Now that I have the dataset myv how do I show it inside the tooltip?

3) Is there any better/cleaner way to achieve what I am trying to do?

Thank you in advance for your time!

Regarding (1), you can use .each to run a function once for each datum in a selection:

    d3.selectAll('.marker')
      .filter(...)
      .each(function(d) { myv.push(d.name); });

Displaying the names inside of the tooltip will require you to do separate selection and then using the myv array as your dataset.

tooltip.selectAll(".name")
  .data(myv)
  // do stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM