Snippets

Piotr Szrajber Smart M.App - Custom Tooltips in BI Map choropleth

Created by Piotr Szrajber last modified
//# sourceURL=custom-tooltip.js
// Custom BI Map Tooltip implementation
// author: Piotr Szrajber <piotr.szrajber@hexagongeospatial.com>
// date: 2016-09-14
/**
* Custom tooltip implementation
* @param {HTMLElement} parentNode Html element that hosts the tooltip. For example document.body
*/
function Tooltip(parentNode) {
    this.el = document.createElement("div");
    this.el.classList.add("gvc-tooltip");
    this.el.style.display = "none";
    parentNode.appendChild(this.el);
}

/**
* Show the tooltip
* @method show
* @param {MouseEvent} e mouse event
* @param {Object} data Key-Value dictionary of data to be shown
*/
Tooltip.prototype.show = function(e, data) {
    var x = e.x || e.clientX,
        y = e.y || e.clientY,
        propertyName,
        propertyValue,
        table,
        row;
    this.el.style.display = "block";
    this.el.style.top = y + "px";
    this.el.style.left = x + "px";
    table = this.el.querySelector("table");
    if (table) this.el.removeChild(table);
    table = document.createElement("table");
    this.el.appendChild(table);
    for (propertyName in data) {
        propertyValue = data[propertyName];
        row = document.createElement("tr");
        row.innerHTML = '<td class="gvc-name">' + propertyName.replace(/_/, " ") + ':</td>&nbsp;<td class="gvc-value">' + propertyValue + '</td>';
        table.appendChild(row);
    }
};

/**
 * Show the tooltip
 * @method hide
 * @param {MouseEvent} e mouse event (unused)
 */
Tooltip.prototype.hide = function(e) {
    this.el.style.display = "none";
};

// find the first choropleth widget and change its tooltip behavior
$GP.bi.stage.findWidgets({
    descriptors: [{
        chartM: {
            chart: "choropleth"
        }
    }]
}, function(widgets) {
    if (!widgets || !widgets[0]) {
        console.error("Nope");
    }

    var tooltip = new Tooltip(document.body);

    var choropleth = widgets[0].chart;

    choropleth.onMouseOver(function(feature, event) {
        if (!tooltip) return;
        tooltip.show(event.originalEvent, feature.properties);
    });
    choropleth.onMouseOut(function(event) {
        if (!tooltip) return;
        tooltip.hide();
    });
}, function(err) {
    console.error(err);
});

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.