将图片添加到Google图表

时间:2015-04-23 13:56:23

标签: javascript charts google-visualization

我使用Google图表API获得以下区域图表。我希望能够在底部动态添加标记,如下所示(橙色)。

enter image description here

HTML会是最好的,但如果不可能的话,可以只针对图像。

这可行吗?

1 个答案:

答案 0 :(得分:1)

我的解决方案是获取所有hAx的坐标,然后在每个坐标上添加svg图像。

jsfidlle

//Get all svg group component as an collection
var g_collection = document.getElementsByTagName('g');

//Convert the collection into array
var g_array = Array.prototype.slice.call( g_collection, 0 );

//Filter the array to get hAxis group
var hAxis = g_array.filter(function(g){
    return g.logicalname && g.logicalname.indexOf("hAxis") > -1 && g.logicalname.indexOf("title") === -1
});

//Draw marker on each hAxis
hAxis.forEach(function(g, index){
    //Create marker using svg image
    var marker= document.createElementNS("http://www.w3.org/2000/svg", "image");

    //Get coordinate
    var x = g.childNodes[0].getAttribute('x');
    var y = g.childNodes[0].getAttribute('y');

    //Set attributes on the marker
    marker.setAttributeNS(null, "x", x - 20);
    marker.setAttributeNS(null, "y", y - 70);
    marker.setAttributeNS("http://www.w3.org/1999/xlink", "href", "image url");
    marker.setAttributeNS(null, "height", "50px"); 
    marker.setAttributeNS(null, "width", "50px"); 
    marker.setAttributeNS(null, "style","cursor:pointer");

    //Add mouse click event listener on the marker
    marker.addEventListener("mousedown", function(e){
        alert("mouse down on marker"+index);
        //add your event code
    });

    //Add the marker in the hAxis group
    g.appendChild(marker);
});