如何在使用 d3 绘制的 SVG 地图上显示国家名称标签?

ats*_*uab 1 javascript svg d3.js

我目前在尝试在 d3 世界地图上显示国家/地区名称时遇到问题。

这是显示国家/地区名称的传单示例的图像。这将是我想添加到我的 d3 版本中的内容。如果可能的话,只需国家名称。如果没有,我总是可以走传单路线,但我想我会先在 d3 尝试。

在此输入图像描述

这是d3版本

在此输入图像描述

这是我目前绘制地图的方式

    // reference to actual element d3 selects
    this.svg = d3.select(this.mapContainer.nativeElement)
        .append('svg')
        .attr('width', this.width)
        .attr('height', this.height)
        .call(zoom)
        .append('g')
        .attr('class', 'map');

    this.projection = d3.geoMercator()
        .scale(225)
        .translate([this.width / 2, this.height / 1.5]);

    const path = d3.geoPath().projection(this.projection);

    let g = this.svg.append('g');

    // if unknown is not in the filter set remove it from the json
    const filteredWorldMapJson = this.worldMapJson.features;

    // features are a list of countries
    // ex: { type: 'Feature', properties: { name: 'United States }, geometry: { type: 'Polygon', coordinates[] }, id: 'USA' }
    let test = g.attr('class', 'countries')
        .selectAll('path')
        .data(filteredWorldMapJson)
        .enter()
        .append('path')
        .attr('d', path)
        .attr('class', d => d.id)
        .style('fill', d => this._mapService.getBinColor(d.id))
        .style('stroke', 'white')
        .style('opacity', 0.8)
        .style('stroke-width', 0.3);

    // id = countries abbreviation
    this.svg.append('path')
        .datum(topojson.mesh(filteredWorldMapJson, (a, b) => a.id !== b.id))
        .attr('class', 'names')
        .attr('d', path);
Run Code Online (Sandbox Code Playgroud)

国家/地区名称是 geojson 的一部分,因此我认为我可以抓住它并以某种方式将它们附加到每个国家/地区

Mic*_*bbs 5

好问题 - 一般来说,您希望从 geojson 文件中解析标签数据(在本例中为国家/地区名称),并使用标签所属地理特征的投影位置来在地图上定位标签。

这是执行此操作的一些代码:

// Filter down the labels by label rank (only show the most important labels)
var labelData = data.features.filter(function(d) {
  return d.properties.labelrank < 4;
});

var labels = grp.selectAll('text.label').data(labelData);

labels
  .enter()
  .append('text')
  .classed('label', true);

labels
  .attr('x', function(d) {
    return projection(d3.geo.centroid(d))[0];
  })
  .attr('y', function(d) {
    return projection(d3.geo.centroid(d))[1];
  })
  .attr('text-anchor', function(d, i) {
    // Randomly align the label
    var idx = Math.round(3 * Math.random());
    return ['start', 'middle', 'end'][idx];
  })
  .text(function(d) {
    return d.properties.admin;
  });

labels.exit().remove();
Run Code Online (Sandbox Code Playgroud)

完整的工作示例在这里http://blockbuilder.org/pnavarrc/75ec1502f51f86c2f43e

带有标签的世界地图