はじめに
http://blogs.yahoo.co.jp/dk521123/35523904.htmlで述べた通り、SVGオブジェクト配下にテキストを表示をする場合、\n や <br> は、改行されない。 地図上でテキストの折り返しを行う。 方法などは、上記の関連記事を参照のこと。
サンプル
http://blogs.yahoo.co.jp/dk521123/35450674.htmlで作成したサンプルコードをベースにしている
<!DOCTYPE html>
<html>
<head>
<style>
.map-info {
font: bold 17px sans-serif;
}
</style>
</head>
<body>
<script src="">http://d3js.org/d3.v3.js">
<script src="">http://d3js.org/topojson.v1.min.js">
<script src="datamaps.world.js"></script>
<div id="container" style="position: relative; width: 1000px; height: 800px;"></div>
<script>
var map = new Datamap({
scope: 'world',
element: document.getElementById('container'),
});
map.addPlugin('bars', function(layer, dataset, options) {
// hold this in a closure
var self = this;
// a class you'll add to the DOM elements
var className = 'bars';
// make a D3 selection.
var bars =
layer
.selectAll(className)
.data(dataset, JSON.stringify );
var lineHeight = 20;
bars
.enter()
.append('text')
.attr("class", "map-info")
.text(function(d) { return d.info; })
.call(convertNewline, self, lineHeight);
});
var dataset = [
{latitude: 35.686533327621, longitude: 139.69192653894, info: 'Japan<br>Tokyo'},
{latitude: -33.873793, longitude: 151.208054, info: 'Australia<br>Sydney'},
{latitude: 41.902784, longitude: 12.496366, info: 'Italia<br>Roma'},
];
map.bars(dataset, {barWidth: 5});
function convertNewline(texts, self, lineHeight) {
texts.each(function() {
var text = d3.select(this),
lines = text.text().split(/<br>/).reverse(),
lineCount = lines.length,
i,
line,
y;
text.text('');
for (i = 0; i < lineCount; i++) {
line = lines[i];
y = i * lineHeight;
text.append('tspan')
.attr({
'x': self.latLngToXY(text.datum().latitude, text.datum().longitude)[0],
'y': self.latLngToXY(text.datum().latitude, text.datum().longitude)[1] - y,
})
.text(line);
}
});
}
</script>
</body>
</html>