Highcharts Highmaps не отображает точки при загрузке второго графика

Ниже приведена моя функция диаграммы JS и html-код. После загрузки html-страницы у меня есть две кнопки. Нажмите на кнопку chartone, диаграмма загружается отлично, и информационная диаграмма каждой страны также работает отлично. Но при переходе к диаграмме с одной на диаграмму две диаграммы загружаются успешно, но информационная диаграмма каждой страны не загружается и показывает ошибку array.prototype.foreach, вызванную нулевым или неопределенным значением.

function chartOne() {
    $.ajax({
        success: function() {
            var jsondata = {

                "data": [{
                        "value": "27",
                        "code": "in",
                        "name": "india",
                        "last_five_month": [{
                                "month": "Jan",
                                "vcount": "30"
                            },
                            {
                                "month": "Feb",
                                "vcount": "80"
                            },
                            {
                                "month": "Mar",
                                "vcount": "50"
                            }
                        ]
                    },
                    {
                        "value": "65778",
                        "code": "ca",
                        "name": "canada",
                        "last_five_month": [{
                                "month": "Jan",
                                "vcount": "20"
                            },
                            {
                                "month": "Feb",
                                "vcount": "10"
                            },
                            {
                                "month": "Mar",
                                "vcount": "60"
                            }
                        ]
                    }
                ]
            };

            var mapChart;
            var countryChart;

            var graphdata = [];
            var graphdataf = [];
            var month;
            var valuecount;
            var countries = {};

            $.each(jsondata.data, function(i, item) {

                var graphval = [];

                var value = item.value;
                var code = item.code;
                var name = item.name;

                graphval.push(code);
                graphval.push(value);
                graphdata.push(graphval);

                $.each(item.last_five_month, function(j, itemval) {


                });
                countries[item.code] = {
                    name: item.name,
                    code3: item.code,
                    data: item.last_five_month
                };
            });

            var data = [];

            for (var code3 in countries) {
                if (countries.hasOwnProperty(code3)) {
                    $.each(countries[code3].data, function(j, itemval) {
                        //var graphvaldata = [];
                        var value = itemval.vcount;
                        var month = itemval.month;

                        data.push({
                            name: countries[code3].name,
                            code3: code3,
                            value: value,
                            year: month
                        });
                    });
                }

            }
            // Wrap point.select to get to the total selected points
            Highcharts.wrap(Highcharts.Point.prototype, 'select', function(proceed) {
                proceed.apply(this, Array.prototype.slice.call(arguments, 1));
                var points = mapChart.getSelectedPoints();
                if (points.length) {
                    if (points.length === 1) {
                        $('#flag').attr('class', 'flag ' + points[0].flag);
                        $('h2').html(points[0].name);
                    } else {
                        $('#flag').attr('class', 'flag');
                        $('h2').html('Comparing countries');

                    }
                    $('.subheader').html('<h4>Historical population</h4><small><em>Shift + Click on map to compare countries</em></small>');

                    if (!countryChart) {
                        countryChart = Highcharts.chart('country-chart', {
                            chart: {
                                height: 250,
                                spacingLeft: 0
                            },
                            credits: {
                                enabled: false
                            },
                            title: {
                                text: null
                            },
                            subtitle: {
                                text: null
                            },
                            xAxis: {
                                tickPixelInterval: 50,
                                crosshair: true
                            },
                            yAxis: {
                                title: null,
                                opposite: true
                            },
                            tooltip: {
                                split: true
                            },
                            plotOptions: {
                                series: {
                                    animation: {
                                        duration: 500
                                    },
                                    marker: {
                                        enabled: false
                                    }
                                    //threshold: 0
                                    //pointStart: categories
                                }
                            }
                        });
                    }


                    $.each(points, function(i, point) {


                        var data,
                            dataRaw = countries[point['hc-key']].data;

                        if (dataRaw) {
                            data = dataRaw.map((p) => parseInt(p.vcount));
                        }

                        // Update
                        if (countryChart.series[i]) {
                            /*$.each(countries[this.code3].data, function (pointI, value) {
                                countryChart.series[i].points[pointI].update(value, false);
                            });*/
                            countryChart.series[i].update({
                                name: this.name,
                                data: data,
                                type: points.length > 1 ? 'line' : 'area'
                            }, false);
                        } else {
                            countryChart.addSeries({
                                name: this.name,
                                data: data,
                                type: points.length > 1 ? 'line' : 'area'
                            }, false);
                        }
                    });
                    while (countryChart.series.length > points.length) {
                        countryChart.series[countryChart.series.length - 1].remove(false);
                    }
                    countryChart.redraw();

                } else {
                    $('#info #flag').attr('class', '');
                    $('#info h2').html('');
                    $('#info .subheader').html('');
                    if (countryChart) {
                        countryChart = countryChart.destroy();
                    }
                }
            });
            // Initiate the map chart
            mapChart = Highcharts.mapChart('container', {

                title: {
                    text: 'Population history by country'
                },

                subtitle: {
                    text: 'Source: <a href="http://data.worldbank.org/indicator/SP.POP.TOTL/countries/1W?display=default">The World Bank</a>'
                },
                /*mapNavigation: {
                    enabled: true,
                    buttonOptions: {
                        verticalAlign: 'left'
                    }
                },*/

                legend: {
                    layout: 'vertical',
                    align: 'left',
                    verticalAlign: 'bootom',
                    floating: true,
                    backgroundColor: '#FFFFFF'
                },
                colorAxis: {
                    type: 'logarithmic',
                    endOnTick: false,
                    startOnTick: false,
                    min: 50000
                },

                tooltip: {
                    footerFormat: '<span style="font-size: 10px">(Click for details)</span>'
                },
                credits: {
                    enabled: false
                },

                series: [{
                    data: graphdata,
                    mapData: Highcharts.maps['custom/world'],
                    joinBy: 'hc-key',
                    name: 'Total Play',
                    allowPointSelect: true,
                    cursor: 'pointer',
                    states: {
                        select: {
                            color: '#a4edba',
                            borderColor: 'black',
                            dashStyle: 'shortdot'
                        }
                    }
                }]
            });
        }
    });
}

function chartTwo() {
    $.ajax({
        success: function() {
            var jsondata = {

                "data": [{
                        "value": "27",
                        "code": "in",
                        "name": "india",
                        "last_five_month": [{
                                "month": "Jan",
                                "vcount": "30"
                            },
                            {
                                "month": "Feb",
                                "vcount": "80"
                            },
                            {
                                "month": "Mar",
                                "vcount": "50"
                            }
                        ]
                    },
                    {
                        "value": "1",
                        "code": "ie",
                        "name": "ireland",
                        "last_five_month": [{
                                "month": "Jan",
                                "vcount": "70"
                            },
                            {
                                "month": "Feb",
                                "vcount": "10"
                            },
                            {
                                "month": "Mar",
                                "vcount": "30"
                            }
                        ]
                    },
                    {
                        "value": "2088",
                        "code": "us",
                        "name": "united states",
                        "last_five_month": [{
                                "month": "Jan",
                                "vcount": "90"
                            },
                            {
                                "month": "Feb",
                                "vcount": "20"
                            },
                            {
                                "month": "Mar",
                                "vcount": "40"
                            }
                        ]
                    },
                    {
                        "value": "65778",
                        "code": "ca",
                        "name": "canada",
                        "last_five_month": [{
                                "month": "Jan",
                                "vcount": "20"
                            },
                            {
                                "month": "Feb",
                                "vcount": "10"
                            },
                            {
                                "month": "Mar",
                                "vcount": "60"
                            }
                        ]
                    }
                ]
            };

            var mapChart;
            var countryChart;

            var graphdata = [];
            var graphdataf = [];
            var month;
            var valuecount;
            var countries = {};

            $.each(jsondata.data, function(i, item) {

                var graphval = [];

                var value = item.value;
                var code = item.code;
                var name = item.name;

                graphval.push(code);
                graphval.push(value);
                graphdata.push(graphval);

                $.each(item.last_five_month, function(j, itemval) {


                });
                countries[item.code] = {
                    name: item.name,
                    code3: item.code,
                    data: item.last_five_month
                };
            });

            var data = [];

            for (var code3 in countries) {
                if (countries.hasOwnProperty(code3)) {
                    $.each(countries[code3].data, function(j, itemval) {
                        //var graphvaldata = [];
                        var value = itemval.vcount;
                        var month = itemval.month;

                        data.push({
                            name: countries[code3].name,
                            code3: code3,
                            value: value,
                            year: month
                        });
                    });
                }

            }
            // Wrap point.select to get to the total selected points
            Highcharts.wrap(Highcharts.Point.prototype, 'select', function(proceed) {
                proceed.apply(this, Array.prototype.slice.call(arguments, 1));
                var points = mapChart.getSelectedPoints();
                if (points.length) {
                    if (points.length === 1) {
                        $('#flag').attr('class', 'flag ' + points[0].flag);
                        $('h2').html(points[0].name);
                    } else {
                        $('#flag').attr('class', 'flag');
                        $('h2').html('Comparing countries');

                    }
                    $('.subheader').html('<h4>Historical population</h4><small><em>Shift + Click on map to compare countries</em></small>');

                    if (!countryChart) {
                        countryChart = Highcharts.chart('country-chart', {
                            chart: {
                                height: 250,
                                spacingLeft: 0
                            },
                            credits: {
                                enabled: false
                            },
                            title: {
                                text: null
                            },
                            subtitle: {
                                text: null
                            },
                            xAxis: {
                                tickPixelInterval: 50,
                                crosshair: true
                            },
                            yAxis: {
                                title: null,
                                opposite: true
                            },
                            tooltip: {
                                split: true
                            },
                            plotOptions: {
                                series: {
                                    animation: {
                                        duration: 500
                                    },
                                    marker: {
                                        enabled: false
                                    }
                                    //threshold: 0
                                    //pointStart: categories
                                }
                            }
                        });
                    }

                    $.each(points, function(i, point) {
                        var data,
                            dataRaw = countries[point['hc-key']].data;

                        if (dataRaw) {
                            data = dataRaw.map((p) => parseInt(p.vcount));
                        }

                        // Update
                        if (countryChart.series[i]) {
                            /*$.each(countries[this.code3].data, function (pointI, value) {
                                countryChart.series[i].points[pointI].update(value, false);
                            });*/
                            countryChart.series[i].update({
                                name: this.name,
                                data: data,
                                type: points.length > 1 ? 'line' : 'area'
                            }, false);
                        } else {
                            countryChart.addSeries({
                                name: this.name,
                                data: data,
                                type: points.length > 1 ? 'line' : 'area'
                            }, false);
                        }
                    });
                    while (countryChart.series.length > points.length) {
                        countryChart.series[countryChart.series.length - 1].remove(false);
                    }
                    countryChart.redraw();

                } else {
                    $('#info #flag').attr('class', '');
                    $('#info h2').html('');
                    $('#info .subheader').html('');
                    if (countryChart) {
                        countryChart = countryChart.destroy();
                    }
                }
            });
            // Initiate the map chart
            mapChart = Highcharts.mapChart('container', {

                title: {
                    text: 'Population history by country'
                },

                subtitle: {
                    text: 'Source: <a href="http://data.worldbank.org/indicator/SP.POP.TOTL/countries/1W?display=default">The World Bank</a>'
                },

                legend: {
                    layout: 'vertical',
                    align: 'left',
                    verticalAlign: 'bootom',
                    floating: true,
                    backgroundColor: '#FFFFFF'
                },
                colorAxis: {
                    type: 'logarithmic',
                    endOnTick: false,
                    startOnTick: false,
                    min: 50000
                },

                tooltip: {
                    footerFormat: '<span style="font-size: 10px">(Click for details)</span>'
                },
                credits: {
                    enabled: false
                },

                series: [{
                    data: graphdata,
                    mapData: Highcharts.maps['custom/world'],
                    joinBy: 'hc-key',
                    name: 'Total Play',
                    allowPointSelect: true,
                    cursor: 'pointer',
                    states: {
                        select: {
                            color: '#a4edba',
                            borderColor: 'black',
                            dashStyle: 'shortdot'
                        }
                    }
                }]
            });
        }
    });
}
<!DOCTYPE html>
<html>
  <head>
    <title>Page Title</title>
    <link href="highmaps.css"/>

    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.highcharts.com/maps/modules/map.js"></script>
    <script src="https://code.highcharts.com/mapdata/custom/world.js"></script>
    <script src="highmaps.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
      $("#onec").click(function(){
         chartOne();
      });

      $("#twoc").click(function(){
          chartTwo();
      });
    });
    </script>
  </head>
  <body>
    <div id="wrapper">
        <div id="container"></div>
        <div id="info">
            <span class="f32"><span id="flag"></span></span>
            <h2></h2>
            <div class="subheader">Click countries to view history</div>
            <div id="country-chart"></div>
        </div>
    </div>
    <div>
      <button id="onec">chart one</button>
      <button id="twoc">chart two</button>
    </div>
  </body>
</html>


person vrock    schedule 25.03.2018    source источник
comment
моя ошибка: Array.prototype.forEach вызывается при нулевом или неопределенном значении   -  person vrock    schedule 25.03.2018


Ответы (1)


Ваша проблема возникает из-за того, что вы переопределяете функцию щелчка внутри друг друга, а страны назначаются внутри каждой из ваших функций. Вам нужно использовать функцию Highcharts.wrap вне ваших функций щелчка. Фиксированный код JS приведен ниже.

var countries = {};

function chartOne() {

    $.ajax({
        success: function () {
            var jsondata = {

                "data": [{
                    "value": "27",
                    "code": "in",
                    "name": "india",
                    "last_five_month": [{
                        "month": "Jan",
                        "vcount": "30"
                    },
                    {
                        "month": "Feb",
                        "vcount": "80"
                    },
                    {
                        "month": "Mar",
                        "vcount": "50"
                    }
                    ]
                },
                {
                    "value": "65778",
                    "code": "ca",
                    "name": "canada",
                    "last_five_month": [{
                        "month": "Jan",
                        "vcount": "20"
                    },
                    {
                        "month": "Feb",
                        "vcount": "10"
                    },
                    {
                        "month": "Mar",
                        "vcount": "60"
                    }
                    ]
                }
                ]
            };

            var mapChart;
            var countryChart;

            var graphdata = [];
            var graphdataf = [];
            var month;
            var valuecount;

            $.each(jsondata.data, function (i, item) {

                var graphval = [];

                var value = item.value;
                var code = item.code;
                var name = item.name;

                graphval.push(code);
                graphval.push(value);
                graphdata.push(graphval);

                $.each(item.last_five_month, function (j, itemval) {


                });
                countries[item.code] = {
                    name: item.name,
                    code3: item.code,
                    data: item.last_five_month
                };
            });

            var data = [];

            for (var code3 in countries) {
                if (countries.hasOwnProperty(code3)) {
                    $.each(countries[code3].data, function (j, itemval) {
                        //var graphvaldata = [];
                        var value = itemval.vcount;
                        var month = itemval.month;

                        data.push({
                            name: countries[code3].name,
                            code3: code3,
                            value: value,
                            year: month
                        });
                    });
                }

            }


            // Initiate the map chart
            mapChart = Highcharts.mapChart('container', {

                title: {
                    text: 'Population history by country'
                },

                subtitle: {
                    text: 'Source: <a href="http://data.worldbank.org/indicator/SP.POP.TOTL/countries/1W?display=default">The World Bank</a>'
                },
                /*mapNavigation: {
                    enabled: true,
                    buttonOptions: {
                        verticalAlign: 'left'
                    }
                },*/

                legend: {
                    layout: 'vertical',
                    align: 'left',
                    verticalAlign: 'bootom',
                    floating: true,
                    backgroundColor: '#FFFFFF'
                },
                colorAxis: {
                    type: 'logarithmic',
                    endOnTick: false,
                    startOnTick: false,
                    min: 50000
                },

                tooltip: {
                    footerFormat: '<span style="font-size: 10px">(Click for details)</span>'
                },
                credits: {
                    enabled: false
                },

                series: [{
                    data: graphdata,
                    mapData: Highcharts.maps['custom/world'],
                    joinBy: 'hc-key',
                    name: 'Total Play',
                    allowPointSelect: true,
                    cursor: 'pointer',
                    states: {
                        select: {
                            color: '#a4edba',
                            borderColor: 'black',
                            dashStyle: 'shortdot'
                        }
                    }
                }]
            });
        }
    });
}

function chartTwo() {
    $.ajax({
        success: function () {
            var jsondata = {

                "data": [{
                    "value": "27",
                    "code": "in",
                    "name": "india",
                    "last_five_month": [{
                        "month": "Jan",
                        "vcount": "30"
                    },
                    {
                        "month": "Feb",
                        "vcount": "80"
                    },
                    {
                        "month": "Mar",
                        "vcount": "50"
                    }
                    ]
                },
                {
                    "value": "1",
                    "code": "ie",
                    "name": "ireland",
                    "last_five_month": [{
                        "month": "Jan",
                        "vcount": "70"
                    },
                    {
                        "month": "Feb",
                        "vcount": "10"
                    },
                    {
                        "month": "Mar",
                        "vcount": "30"
                    }
                    ]
                },
                {
                    "value": "2088",
                    "code": "us",
                    "name": "united states",
                    "last_five_month": [{
                        "month": "Jan",
                        "vcount": "90"
                    },
                    {
                        "month": "Feb",
                        "vcount": "20"
                    },
                    {
                        "month": "Mar",
                        "vcount": "40"
                    }
                    ]
                },
                {
                    "value": "65778",
                    "code": "ca",
                    "name": "canada",
                    "last_five_month": [{
                        "month": "Jan",
                        "vcount": "20"
                    },
                    {
                        "month": "Feb",
                        "vcount": "10"
                    },
                    {
                        "month": "Mar",
                        "vcount": "60"
                    }
                    ]
                }
                ]
            };

            var mapChart;
            var countryChart;

            var graphdata = [];
            var graphdataf = [];
            var month;
            var valuecount;


            $.each(jsondata.data, function (i, item) {

                var graphval = [];

                var value = item.value;
                var code = item.code;
                var name = item.name;

                graphval.push(code);
                graphval.push(value);
                graphdata.push(graphval);

                $.each(item.last_five_month, function (j, itemval) {


                });
                countries[item.code] = {
                    name: item.name,
                    code3: item.code,
                    data: item.last_five_month
                };
            });

            var data = [];

            for (var code3 in countries) {
                if (countries.hasOwnProperty(code3)) {
                    $.each(countries[code3].data, function (j, itemval) {
                        //var graphvaldata = [];
                        var value = itemval.vcount;
                        var month = itemval.month;

                        data.push({
                            name: countries[code3].name,
                            code3: code3,
                            value: value,
                            year: month
                        });
                    });
                }

            }

            // Initiate the map chart
            mapChart = Highcharts.mapChart('container', {

                title: {
                    text: 'Population history by country'
                },

                subtitle: {
                    text: 'Source: <a href="http://data.worldbank.org/indicator/SP.POP.TOTL/countries/1W?display=default">The World Bank</a>'
                },

                legend: {
                    layout: 'vertical',
                    align: 'left',
                    verticalAlign: 'bootom',
                    floating: true,
                    backgroundColor: '#FFFFFF'
                },
                colorAxis: {
                    type: 'logarithmic',
                    endOnTick: false,
                    startOnTick: false,
                    min: 50000
                },

                tooltip: {
                    footerFormat: '<span style="font-size: 10px">(Click for details)</span>'
                },
                credits: {
                    enabled: false
                },

                series: [{
                    data: graphdata,
                    mapData: Highcharts.maps['custom/world'],
                    joinBy: 'hc-key',
                    name: 'Total Play',
                    allowPointSelect: true,
                    cursor: 'pointer',
                    states: {
                        select: {
                            color: '#a4edba',
                            borderColor: 'black',
                            dashStyle: 'shortdot'
                        }
                    }
                }]
            });
        }
    });
}


// Wrap point.select to get to the total selected points
Highcharts.wrap(Highcharts.Point.prototype, 'select', function (proceed) {
    proceed.apply(this, Array.prototype.slice.call(arguments, 1));
    var mapChart = $("#container").highcharts();
    var points = mapChart.getSelectedPoints();

    if (points.length) {
        if (points.length === 1) {
            $('#flag').attr('class', 'flag ' + points[0].flag);
            $('h2').html(points[0].name);
        } else {
            $('#flag').attr('class', 'flag');
            $('h2').html('Comparing countries');

        }
        $('.subheader').html('<h4>Historical population</h4><small><em>Shift + Click on map to compare countries</em></small>');
        var countryChart;
        if (!countryChart) {
            countryChart = Highcharts.chart('country-chart', {
                chart: {
                    height: 250,
                    spacingLeft: 0
                },
                credits: {
                    enabled: false
                },
                title: {
                    text: null
                },
                subtitle: {
                    text: null
                },
                xAxis: {
                    tickPixelInterval: 50,
                    crosshair: true
                },
                yAxis: {
                    title: null,
                    opposite: true
                },
                tooltip: {
                    split: true
                },
                plotOptions: {
                    series: {
                        animation: {
                            duration: 500
                        },
                        marker: {
                            enabled: false
                        }
                        //threshold: 0
                        //pointStart: categories
                    }
                }
            });
        }

        $.each(points, function (i, point) {
            var data,
                dataRaw = countries[point['hc-key']].data;

            if (dataRaw) {
                data = dataRaw.map((p) => parseInt(p.vcount));
            }

            // Update
            if (countryChart.series[i]) {
                /*$.each(countries[this.code3].data, function (pointI, value) {
                    countryChart.series[i].points[pointI].update(value, false);
                });*/
                countryChart.series[i].update({
                    name: this.name,
                    data: data,
                    type: points.length > 1 ? 'line' : 'area'
                }, false);
            } else {
                countryChart.addSeries({
                    name: this.name,
                    data: data,
                    type: points.length > 1 ? 'line' : 'area'
                }, false);
            }
        });
        while (countryChart.series.length > points.length) {
            countryChart.series[countryChart.series.length - 1].remove(false);
        }
        countryChart.redraw();

    } else {
        $('#info #flag').attr('class', '');
        $('#info h2').html('');
        $('#info .subheader').html('');
        if (countryChart) {
            countryChart = countryChart.destroy();
        }
    }
});

$(document).ready(function () {
    $("#onec").click(function () {
        chartOne();
    });

    $("#twoc").click(function () {
        chartTwo();
    });
});
person Guruparan Giritharan    schedule 25.03.2018
comment
Это работает. Это демонстрационный код. В реальном приложении я фильтрую данные json и передаю функцию диаграммы, так что это будет работать? - person vrock; 25.03.2018
comment
Должно работать, всегда используйте общие функции highchart снаружи, особенно такие, как стилизация и все такое. также, если это отвечает на ваш вопрос, пожалуйста, выберите его :) - person Guruparan Giritharan; 25.03.2018
comment
Есть одна проблема, связанная с тем, что данные старой карты мира не ясны, когда мы нажимаем кнопку на диаграмме два. - person vrock; 29.03.2018