Добавить маркер вертикальной линии в линейку Google Visualization, которая перемещается при движении мыши?

Можно ли отобразить вертикальный маркер линии, показывающий текущее значение оси X на LineChart и движущийся при перемещении мыши?

Заранее спасибо.

1 ответ

Решение

Хотя раньше это было сложно, недавнее обновление API делает это намного проще! Вам нужно использовать обработчик события mouseover, чтобы получить координаты мыши, и новый ChartLayoutInterface, чтобы перевести координаты в значения диаграммы. Вот пример кода:

[edit - исправлена ​​проблема кросс-браузерной совместимости]*[edit - обновлено для получения значений точек рядом с линией аннотации]*

function drawChart() {
    // Create and populate the data table.
    var data = new google.visualization.DataTable();
    data.addColumn('number', 'x');
    // add an "annotation" role column to the domain column
    data.addColumn({type: 'string', role: 'annotation'});
    data.addColumn('number', 'y');

    // add 100 rows of pseudorandom data
    var y = 50;
    for (var i = 0; i < 100; i++) {
        y += Math.floor(Math.random() * 5) * Math.pow(-1, Math.floor(Math.random() * 2));
        data.addRow([i, null, y]);
    }
    // add a blank row to the end of the DataTable to hold the annotations
    data.addRow([null, null, null]);
    // get the index of the row used for the annotations
    var annotationRowIndex = data.getNumberOfRows() - 1;

    var options = {
        annotation: {
            1: {
                // set the style of the domain column annotations to "line"
                style: 'line'
            }
        },
        height: 400,
        width: 600
    };

    // create the chart
    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

    // create 'ready' event listener to add mousemove event listener to the chart
    var runOnce = google.visualization.events.addListener(chart, 'ready', function () {
        google.visualization.events.removeListener(runOnce);
        // create mousemove event listener in the chart's container
        // I use jQuery, but you can use whatever works best for you
        $('#chart_div').mousemove(function (e) {
            var xPos = e.pageX - container.offsetLeft;
            var yPos = e.pageY - container.offsetTop;
            var cli = chart.getChartLayoutInterface();
            var xBounds = cli.getBoundingBox('hAxis#0#gridline');
            var yBounds = cli.getBoundingBox('vAxis#0#gridline');

            // is the mouse inside the chart area?
            if (
                (xPos >= xBounds.left || xPos <= xBounds.left + xBounds.width) &&
                (yPos >= yBounds.top || yPos <= yBounds.top + yBounds.height) 
            ) {
                // if so, draw the vertical line here
                // get the x-axis value at these coordinates
                var xVal = cli.getHAxisValue(xPos);
                // set the x-axis value of the annotation
                data.setValue(annotationRowIndex, 0, xVal);
                // set the value to display on the line, this could be any value you want
                data.setValue(annotationRowIndex, 1, xVal.toFixed(2));

                // get the data value (if any) at the line
                // truncating xVal to one decimal place,
                // since it is unlikely to find an annotation like that aligns precisely with the data
                var rows = data.getFilteredRows([{column: 0, value: parseFloat(xVal.toFixed(1))}]);
                if (rows.length) {
                    var value = data.getValue(rows[0], 2);
                    // do something with value
                }

                // draw the chart with the new annotation
                chart.draw(data, options);
            }
        });
    });

    // draw the chart
    chart.draw(data, options);
}

Посмотреть это работает здесь: http://jsfiddle.net/asgallant/tVCv9/12

Другие вопросы по тегам