簡體   English   中英

如何在使用d3繪制的SVG地圖上顯示國家/地區名稱標簽?

[英]How to display country name labels on an SVG map drawn with d3?

我目前無法在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);

國名是geojson的一部分,所以我認為我可以抓住它並以某種方式將它們附加到每個國家

好問題 - 通常,您希望從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();

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

世界地圖與標簽

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM