对d3.js中的SVG元素进行聚类会产生意想不到的结果



所以我试图为一个使用d3.js、polymaps和Coffeescrapt的项目做一些地图标记聚类。

我根据底层数据计算集群,然后将集群数组作为.data(集群)传递到d3中

聚类的位置似乎还可以。初始缩放级别的聚类似乎还可以,根据我的知识,它是100%准确的。当我更改缩放级别时,乍一看一切似乎都很好,但当我悬停在圆圈上时,描述似乎与它们所在的位置不匹配,路线以前所在的位置似乎与它们现在所在的位置也不匹配。

我在http://bl.ocks.org/3161013其中包括完整的代码。

我看到了两个主要的失败点:集群和更新SVG。

集群的代码相当简单,基于Mark Tuupola的代码,但使用的是coffeescript而不是php。

  cluster: (elements, distance) ->
    currentElements = elements.slice(0)
    pixelDistance = @pixelDistance()
    distLat = distance * pixelDistance.lat
    distLon = distance * pixelDistance.lon 
    clustered = []
    while currentElements.length > 0
      stop = currentElements.shift()
      cluster = []
      cluster.push stop
      i = 0
      while i < currentElements.length
        if Math.abs(currentElements[i].lat - stop.lat) < distLat and Math.abs(currentElements[i].lon - stop.lon) < distLon
          aStop = currentElements.splice i,1
          cluster.push aStop[0]
          i--
        i++
      clustered.push cluster  
    clustered   

SVG更新的代码看起来相当直接的d3代码。每当地图被移动时,就会调用此更新方法。如果缩放发生了变化,或者预聚集的数据发生了改变,我们将重新聚集和布局,否则我们只平移现有的点。

  update: ->
    if not @stops
      @stops = []
    if not @prevNumStops
      @prevNumStops = 0
    if not @prevZoom
      @prevZoom = 0

    if @zoomLevel() != @prevZoom or @prevNumStops != @stops.length
      @prevZoom = @zoomLevel()
      @prevNumStops = @stops.length 
      start = new Date()
      @clusters = @cluster(@stops,10)
      console.log @clusters
      console.log "clustering: " + ((new Date()) - start)
      start = new Date()
      marker = @selector.selectAll("g").data(@clusters)
      marker.enter().append("g")
      .append("circle")
      .attr("class", "stop no-tip")
      marker.exit().remove()
      @selector.selectAll("g").selectAll("circle")
      .attr('r', (cluster) -> if cluster.length > 1 then 5 else 3.5)
      .attr("text", (cluster) -> "<ul>" + ((("<li>" + route + "</li>") for route in stop.routes).join("") for stop in cluster).join("") + "</ul>")
    @selector.selectAll("g").attr("transform", (cluster) => 
      @transform cluster[0]
    )

我觉得这里可能缺少一些简单的东西,但我对d3还很陌生。

当数据发生变化时,现有标记中的"circle"元素不会更新(d3默认使用索引来确定是添加(进入)、删除(退出)还是更新(默认)新元素)。这将使文本成为上一缩放级别上已存在的所有元素的旧文本。

它应该使用以下代码:

marker = @selector.selectAll("g").data(@clusters)
# update existing 'g' elements
marker.select('circle')
.attr('r', your_cluster_size_function)
.attr("text", your_text_function)

# add new 'g' elements
marker.enter().append("g")
.append("circle")
.attr("class", "stop no-tip")
.attr('r', your_cluster_size_function)
.attr("text", your_text_function)
# remove 'g' elements if there are too many
marker.exit().remove()

最新更新