Tom Gullen
Tom Gullen

Reputation: 61729

Add image to google chart

I have the following area chart using the Google charts API. I'd like to be able to dynamically add markers along the bottom like follows (in orange).

enter image description here

HTML would be best, but can settle for just images if that's not possible.

Is this doable?

Upvotes: 1

Views: 1080

Answers (1)

Edward Lee
Edward Lee

Reputation: 951

My solution is to get coordinates of all hAxes and then add svg image on each coordinate.

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);
});

Upvotes: 1

Related Questions