答案 0 :(得分:0)
没有任何选项可以更改图例在GeoChart上的对齐方式,
但可以手动移动。
但是,图表会将其移回活动的原始位置,
例如将鼠标移至某个国家/地区时。
在这种情况下,必须使用MutationObserver
,
每次绘制图例时都要移动图例。
请参阅以下工作片段...
google.charts.load('current', {
packages: ['geochart'],
mapsApiKey: 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200],
['United States', 300],
['Brazil', 400],
['Canada', 500],
['France', 600],
['RU', 700]
]);
var options = {
height: 500,
width: 900
};
var container = document.getElementById('regions_div');
var chart = new google.visualization.GeoChart(container);
var observer = new MutationObserver(function () {
var xCoord;
var xDiff;
// move legend bar
var rects = container.getElementsByTagName('rect');
Array.prototype.forEach.call(rects, function(rect) {
if (rect.getAttribute('y') !== '0') {
xCoord = (options.width / 2) - (parseFloat(rect.getAttribute('width')) / 2);
xDiff = xCoord - parseFloat(rect.getAttribute('x'));
rect.setAttribute('x', xCoord);
}
});
// move legend labels
var labels = container.getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label) {
if (label.getAttribute('font-weight') !== 'bold') {
for (var i = 0; i < data.getNumberOfRows(); i++) {
if (label.textContent === data.getFormattedValue(i, 1)) {
xCoord = parseFloat(label.getAttribute('x'));
label.setAttribute('x', xCoord + xDiff);
break;
}
}
}
});
// move legend indicator (triangle shown on hover)
var paths = container.getElementsByTagName('path');
Array.prototype.forEach.call(paths, function(path) {
if ((path.getAttribute('fill') === '#000000') && (path.getAttribute('stroke') === '#000000') && (path.getAttribute('stroke-width') === '1')) {
var d = path.getAttribute('d');
var coords = d.split(',');
var x1 = coords[0].split('M');
var x2 = coords[1].split('L');
var x3 = coords[2].split('L');
var d1 = parseFloat(x1[1]) + xDiff;
var d2 = parseFloat(x2[1]) + xDiff;
var d3 = parseFloat(x3[1]) + xDiff;
d = 'M' + d1 + ',' + x2[0] + 'L' + d2 + ',' + x3[0] + 'L' + d3 + ',' + coords[3];
path.setAttribute('d', d);
}
});
});
observer.observe(container, {
childList: true,
subtree: true
});
chart.draw(data);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="regions_div" style="width: 900px; height: 500px;"></div>