S
S
Semyon Leonidovich Dynka2014-04-23 02:47:26
PHP
Semyon Leonidovich Dynka, 2014-04-23 02:47:26

How to display visits/views statistics from Yandex.Metrica as a graph?

Hello Toaster!
I set out to show the statistics of visits and views on my site, and even in the form of a graph. While I look in the direction of Y. Metrika, because they have a friendlier API (in my opinion, yes, although I am just starting to work with all this).
Found this article. Received and created everything you need to get started (token, password and application ID).
I think to display the chart using amCharts , but so far I have not even figured it out.
I got stuck at the stage of receiving data from Yandex.Metrica. Out of grief, I came to the Toaster. I perfectly understand the task and can describe it competently and clearly, but, alas, there is not enough knowledge for self-implementation (but I am learning, really). And since this is the first question for me here (I was a reader), the site suggests that everyone wants details. That's why I write. So.
I would like to collect data for the interval of a month. But not calendar, but from the current date. Those. Today minus 30 days .
As far as I understand, amCharts needs this type of output, especially since I will have 2 charts.

etc
{
  name: '22.04',
  visits: 52300,
  hits: 94800
},
{
  name: '23.04',
  visits: 52300,
  hits: 94800
}
etc

Well, actually, the question is: how to do / get it?
To simplify the search for answers and still at least some savings for knowledgeable people, a link to the Yandex.Metrica API documentation.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2014-12-19
@bande

I myself am not strong in this all, but I made a conclusion to the site from the metric.
First, I made a file called metrica.php and put the following code into it

<?php
$today=date("Ymd");
$metrika_url = "http://api-metrika.yandex.ru/stat/traffic/summary.json?id=айди_вашего_счетчика&pretty=1&date1=Дата_начала_выборки_данных_со_счетчика&date2=$today&oauth_token=ваш токен";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $metrika_url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$metrika = curl_exec ($ch);
curl_close ($ch);

$metrika_o = json_decode($metrika);


header('Content-Type: application/json');
echo 'jsonCallback2('. $metrika . ')';

After we create a page where this data will be displayed.
in javascript write this
<script type="text/javascript">
    var link2PHP = "путь_к_файлу/metrika.php";
    var datas2 = [];
    $.ajax ({
        type: "GET",
        url:link2PHP,
        dataType: "jsonp",
        async: false,
        contentType: "application/json",
        jsonp: "callback",
        jsonpCallback: 'jsonCallback2',
        contentType: "application/json",
        success: function(json) {
            $.each(json.data.reverse(), function (index,value){

                var obj2 = {


                    'date2': value.date,
                    'visits2': value.visits,
                    'visitors2': value.visitors

                };

                datas2.push(obj2);
                console.log(obj2)

            });
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(thrownError);
        }
    });

And after the settings themselves for the chart
var chart = AmCharts.makeChart("chartdiv", {
        "pathToImages": "путь к картинкам графика",
        "type": "serial",
        "theme": "light",
        language: "ru",
        "titles": [{
            "text": "Я.Метрика (Статистика посещений и посетителей)",
            "size": 15
        }],
        "legend": {
            "equalWidths": true,
            "useGraphSettings": true,
            "valueAlign": "right",
            "valueWidth": 120

        },
        "dataProvider":datas2,

        "valueAxes": [ {
            "id": "visitsAxis",
            "axisAlpha": 0,
            "gridAlpha": 0,
            "labelsEnabled": false,
            "position": "left"
        }, {
            "id": "visitorsAxis",
            "axisAlpha": 0,
            "gridAlpha": 0,
            "inside": false,
            "position": "right",
            "title": "Количество"
        }],
        "graphs": [  {
            "bullet": "round",
            "bulletBorderAlpha": 1,
            "balloonText": "Посетителей:",

            "legendPeriodValueText": "Всего: ",
            "legendValueText": "",
            "title": "Посетителей",
            "fillAlphas": 0.6,
            "valueField": "visitors2",
            "valueAxis": "visitorsAxis"
        },
            {
            "balloonText": "Посещений:",
            "bullet": "round",
            "bulletBorderAlpha": 1,
            "useLineColorForBulletBorder": true,
            "bulletColor": "#FFFFFF",
            "bulletSizeField": "townSize",
            "dashLengthField": "dashLength",

            "labelPosition": "right",
            "legendPeriodValueText": "Всего: ",
            "legendValueText": "",
            "title": "Посещений",
            "fillAlphas": 0,
            "valueField": "visits2",
            "valueAxis": "visitorsAxis"
        }],
        "chartScrollbar": {gridCount: 7,

            scrollbarHeight: 25,
            graphType: "line",
            usePeriod: "WW",
            backgroundColor: "#333",
            graphFillColor: "#666",
            graphFillAlpha: 0.5,
            gridColor: "#555",
            gridAlpha: 1,
            selectedBackgroundColor: "#444",
            selectedGraphFillAlpha: 1
        },
        "chartCursor": {
            "categoryBalloonDateFormat": "DD MMM",
            "cursorAlpha": 0.1,
            "cursorColor":"#000000",
            "fullWidth":true,
            "valueBalloonsEnabled": true,
            "zoomable": true
        },
        "dataDateFormat": "YYYYMMDD",
        "categoryField": "date2",
        "categoryAxis": {
            "dateFormats": [{
                "period": "DD",
                "format": "DD"
            }, {
                "period": "WW",
                "format": "MMM DD"
            }, {
                "period": "MM",
                "format": "MMM"
            }, {
                "period": "YYYY",
                "format": "YYYY"
            }],
            "parseDates": true,
            "minorGridEnabled": true,
            "gridCount":50,
            "autoGridCount": false,
            "axisColor": "#000",
            "gridAlpha": 0.2,
            "gridColor": "#000"

        },



        amExport: {
            top: -4,
            right: -6
        }


    });

Of course, you can paint and explain everything - but I think you can figure out what goes where and why.
Well, in the body of the file itself, we create <div id=""chartdiv></div>
Where the chart itself will be uploaded.

R
RJs45, 2014-04-23
@RJs45

In my opinion, you need this API method: api.yandex.ru/metrika/doc/ref/stat/traffic-summary.xml
Get a beautiful array that you feed to amCharts

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question