【问题标题】:Random loading of labels for cities随机加载城市标签
【发布时间】:2023-06-05 10:55:01
【问题描述】:

我有一张包含德国和叙利亚各州及其城市的世界地图。如您所见,现在它们完全随机加载。

部分加载德国城市是因为缺少标签

叙利亚城市根本没有装载。当我重新加载它时,它会随机成为我发布的图片之一。

例如,这是我调用德国的函数。

  d3.json("germany.topo.json", function(error, ger){
    if (error) throw error;
    var states = topojson.feature(ger, ger.objects.states_germany),
        cities = topojson.feature(ger, ger.objects.cities_germany);

    g.selectAll(".states")
        .data(states.features)
        .enter()
        .append("path")
        .attr("class", "state")
        .attr("class", function(d) { return "state " + d.id; })
        .attr("d", path);
    g.append("path")
        .datum(cities)
        .attr("d", path.pointRadius('0.35'))
        .attr("class", "city");

      g.selectAll(".place-label")
          .data(cities.features)
          .enter().append("text")
          .attr("class", "place-label")
          .attr("transform", function(d) { return "translate(" + projection(d.geometry.coordinates) + ")"; })
          .attr("dy", ".35em")
          .text(function(d) { return d.properties.name; });
  });

日期是here

我可以部分重现此错误。也许你可以看看并告诉我为什么它不能正常工作。 提前致谢

【问题讨论】:

    标签: javascript d3.js topojson


    【解决方案1】:

    你遇到的问题是这个电话的结果,而且你在德国和叙利亚的城市都在重复这个事实:

    g.selectAll(".place-label")
        .data(cities.features)
        .enter().append("text")
        .attr("class", "place-label")
        .attr("transform", function(d) { return "translate(" + projection(d.geometry.coordinates) + ")"; })
        .attr("dy", ".35em")
        .text(function(d) { return d.properties.name; });
    

    您在对d3.json 的不同调用中选择了所有具有“place-label”类的对象,从而弄乱了您的选择。相反,请尝试以下操作:

    // For German cities
    g.selectAll(".german-place-label")
    
    // For Syrian cities
    g.selectAll(".syrian-place-label")
    

    这似乎解决了您的问题,尽管您可能会考虑重写您的代码,这样您只需要一次调用添加所有城市,而不是两个单独的、几乎相同的调用。

    【讨论】:

      最近更新 更多