世界の測量

Sibling of "Relevant, Timely, and Accurate, " but much lighter and shorter ※自らの所属する組織の見解を示すものでない

「D3 x Leaflet で SVG text」習作

D3 x Leaflet x OSM restaurants x Digital Japan を作成した。

ポイント

次のようにして、Leaflet の重ねあわせ情報ペーンにSVG g要素を挿入している

var svg = d3.select(map.getPanes().overlayPane).append('svg')
var g = svg.append('g').attr('class', 'leaflet-zoom-hide');

D3で、GeoJSONデータをSVG text要素にして挿入している

function project(x) {
  var point = map.latLngToLayerPoint(new L.LatLng(x[1], x[0]));
  return [point.x, point.y];
}

d3.json("data2.geojson", function(collection) {
  var bounds = d3.geo.bounds(collection);

  var text = g.selectAll("text")
      .data(collection.features)
    .enter().append("text");

  map.on("viewreset", reset);
  reset();

  // Reposition the SVG to cover the features.
  function reset() {
    var bottomLeft = project(bounds[0]),
        topRight = project(bounds[1]);

    svg.attr("width", topRight[0] - bottomLeft[0])
       .attr("height", bottomLeft[1] - topRight[1])
       .style("margin-left", bottomLeft[0] + "px")
       .style("margin-top", topRight[1] + "px");
    g.attr("transform", "translate(" + -bottomLeft[0] + 
           "," + -topRight[1] + ")");

    text.attr('x', function(d) {
          return project(d['geometry']['coordinates'])[0];})
        .attr('y', function(d) {
          return project(d['geometry']['coordinates'])[1];})
        .text(function(d) {
          return '←' + d['properties']['name'];});
  }
});

SVGなのでスタイルシートも効くし、文字ごとの座標指定などもできる。ただし、重くなる傾向はある。