Как добавить правую легенду на карту США, которая показывает названия восточных штатов? - PullRequest
0 голосов
/ 10 апреля 2020

Я могу сгенерировать карту США, но всякий раз, когда я пытаюсь добавить пользовательскую карту, используемую в этой скрипте JS, мой код прерывается с ошибкой, которая говорит: «функция не определена». Я хочу создать правую легенду с именами малых состояний:

http://jsfiddle.net/q5zhbmr3/

Вот рабочий пример моего кода: https://codepen.io/MartinLawrence/pen/yLYLWLz?editors=0010

Если у кого-нибудь есть какие-либо предложения о том, как применить этот код для моей конкретной ситуации c, я был бы очень признателен. Заранее спасибо!

var data = [
    ['us-ma', 0],
    ['us-wa', 1],
    ['us-ca', 2],
    ['us-or', 3],
    ['us-wi', 4],
    ['us-me', 5],
    ['us-mi', 6],
    ['us-nv', 7],
    ['us-nm', 8],
    ['us-co', 9],
    ['us-wy', 10],
    ['us-ks', 11],
    ['us-ne', 12],
    ['us-ok', 13],
    ['us-mo', 14],
    ['us-il', 15],
    ['us-in', 16],
    ['us-vt', 17],
    ['us-ar', 18],
    ['us-tx', 19],
    ['us-ri', 20],
    ['us-al', 21],
    ['us-ms', 22],
    ['us-nc', 23],
    ['us-va', 24],
    ['us-ia', 25],
    ['us-md', 26],
    ['us-de', 27],
    ['us-pa', 28],
    ['us-nj', 29],
    ['us-ny', 30],
    ['us-id', 31],
    ['us-sd', 32],
    ['us-ct', 33],
    ['us-nh', 34],
    ['us-ky', 35],
    ['us-oh', 36],
    ['us-tn', 37],
    ['us-wv', 38],
    ['us-dc', 39],
    ['us-la', 40],
    ['us-fl', 41],
    ['us-ga', 42],
    ['us-sc', 43],
    ['us-mn', 44],
    ['us-mt', 45],
    ['us-nd', 46],
    ['us-az', 47],
    ['us-ut', 48],
    ['us-hi', 49],
    ['us-ak', 50],
    ['undefined', 51],
    ['undefined', 52],
    ['undefined', 53],
    ['undefined', 54],
    ['undefined', 55],
    ['undefined', 56],
    ['undefined', 57],
    ['undefined', 58],
    ['undefined', 59],
    ['undefined', 60]
  ],
  mapData = Highcharts.geojson(Highcharts.maps['countries/us/custom/us-small']);

$.each(mapData, function() {
  var path = this.path,
    copy = {
      path: path
    };

  // This point has a square legend to the right
  if (path[1] === 9727) {

    // Identify the box
    Highcharts.seriesTypes.map.prototype.getBox.call({}, [copy]);

    // Place the center of the data label in the center of the point legend box
    this.middleX = ((path[1] + path[4]) / 2 - copy._minX) / (copy._maxX - copy._minX);
    this.middleY = ((path[2] + path[7]) / 2 - copy._minY) / (copy._maxY - copy._minY);
  }

  // Tag it for joining
  this.ucName = this.name.toUpperCase();
});

// Create the chart
Highcharts.mapChart('container', {
  title: {
    text: 'Highmaps basic demo'
  },
  subtitle: {
    text: 'Source map: <a href="http://code.highcharts.com/mapdata/countries/us/custom/us-small.js">United States of America, small</a>'
  },
  mapNavigation: {
    enabled: true,
    buttonOptions: {
      verticalAlign: 'bottom'
    }
  },
  colorAxis: {
    min: 0
  },
  series: [{
    data: data,
    mapData: mapData,
    name: 'Random data',
    states: {
      hover: {
        color: '#BADA55'
      }
    },
    dataLabels: {
      enabled: true,
      formatter: function() {
        return this.point.properties['hc-a2'];
      }
    }
  }, {
    name: 'Separators',
    type: 'mapline',
    data: Highcharts.geojson(Highcharts.maps['countries/us/custom/us-small'], 'mapline'),
    color: 'silver',
    showInLegend: false,
    enableMouseTracking: false
  }]
});

Текущий код, который я использую:

function addElement(parentId, elementTag, elementId, className, html, width, height) {
    // Adds an element to the document
    var p = document.getElementById(parentId);
    var newElement = document.createElement(elementTag);
    newElement.setAttribute('id', elementId);
    newElement.setAttribute('class', className);
    newElement.innerHTML = html;

    if (width != undefined || height != undefined) {
        var style = "";
        if (width != undefined && width != "") {
            style += "width:" + width + "px;"
        }

        if (height != undefined && width != height) {
            style += "height:" + height + "px;"
        }

        newElement.setAttribute('style', style);
    }

    p.appendChild(newElement);
}

var lang = 1;
var categoryLabel = 'Category';

(function() {
    var htmlTemplate = "<div id='vis-BusinessConcentration'></div>";

    var width = "-1";

    var height = "-1";

    addElement("BusinessConcentration", "div", "vis", "visualization-container", htmlTemplate, width, height);

    if ("BusinessConcentration" == "RiskRatingBarometerIndustry" || "BusinessConcentration" == "RiskRatingBarometerSector" || "BusinessConcentration" == "BusinessConcentration") {
        setTimeout(createChart(), 1000);
    } else {
        createChart();
    }

    function createChart() {

        if (typeof window['Highcharts'] !== 'undefined') {



            var optionsNew = {
                "series": [{
                    "allAreas": false,
                    "data": [{
                        "name": "Alabama",
                        "value": 1.2
                    }, {
                        "name": "Alaska",
                        "value": 0.3
                    }, {
                        "name": "Arizona",
                        "value": 1.2
                    }, {
                        "name": "Arkansas",
                        "value": 0.7
                    }, {
                        "name": "California",
                        "value": 12.0
                    }, {
                        "name": "Colorado",
                        "value": 1.2
                    }, {
                        "name": "Connecticut",
                        "value": 1.3
                    }, {
                        "name": "Delaware",
                        "value": 0.3
                    }, {
                        "name": "District of Columbia",
                        "value": 0.3
                    }, {
                        "name": "Florida",
                        "value": 5.5
                    }, {
                        "name": "Georgia",
                        "value": 2.7
                    }, {
                        "name": "Hawaii",
                        "value": 0.5
                    }, {
                        "name": "Idaho",
                        "value": 0.4
                    }, {
                        "name": "Illinois",
                        "value": 4.2
                    }, {
                        "name": "Indiana",
                        "value": 1.5
                    }, {
                        "name": "Iowa",
                        "value": 0.9
                    }, {
                        "name": "Kansas",
                        "value": 0.8
                    }, {
                        "name": "Kentucky",
                        "value": 1.2
                    }, {
                        "name": "Louisiana",
                        "value": 1.4
                    }, {
                        "name": "Maine",
                        "value": 0.6
                    }, {
                        "name": "Maryland",
                        "value": 1.9
                    }, {
                        "name": "Massachusetts",
                        "value": 2.1
                    }, {
                        "name": "Michigan",
                        "value": 2.8
                    }, {
                        "name": "Minnesota",
                        "value": 1.4
                    }, {
                        "name": "Mississippi",
                        "value": 0.7
                    }, {
                        "name": "Missouri",
                        "value": 1.6
                    }, {
                        "name": "Montana",
                        "value": 0.4
                    }, {
                        "name": "Nebraska",
                        "value": 0.6
                    }, {
                        "name": "Nevada",
                        "value": 0.5
                    }, {
                        "name": "New Hampshire",
                        "value": 0.4
                    }, {
                        "name": "New Jersey",
                        "value": 3.9
                    }, {
                        "name": "New Mexico",
                        "value": 0.4
                    }, {
                        "name": "New York",
                        "value": 16.0
                    }, {
                        "name": "North Carolina",
                        "value": 2.9
                    }, {
                        "name": "North Dakota",
                        "value": 0.3
                    }, {
                        "name": "Ohio",
                        "value": 3.1
                    }, {
                        "name": "Oklahoma",
                        "value": 0.9
                    }, {
                        "name": "Oregon",
                        "value": 1.1
                    }, {
                        "name": "Pennsylvania",
                        "value": 4.1
                    }, {
                        "name": "Rhode Island",
                        "value": 0.3
                    }, {
                        "name": "South Carolina",
                        "value": 1.3
                    }, {
                        "name": "South Dakota",
                        "value": 0.3
                    }, {
                        "name": "Tennessee",
                        "value": 1.6
                    }, {
                        "name": "Texas",
                        "value": 5.3
                    }, {
                        "name": "Utah",
                        "value": 0.6
                    }, {
                        "name": "Vermont",
                        "value": 0.3
                    }, {
                        "name": "Virginia",
                        "value": 2.3
                    }, {
                        "name": "Washington",
                        "value": 2.4
                    }, {
                        "name": "West Virginia",
                        "value": 0.5
                    }, {
                        "name": "Wisconsin",
                        "value": 1.6
                    }, {
                        "name": "Wyoming",
                        "value": 0.1
                    }],
                    "dataLabels": "1px contrast"
                }],
                "colorAxis": {
                    "min": 0,
                    "max": 16.0,
                    "tickLength": 5,
                    "tickInterval": 5,
                    "tickAmount": 4
                }
            };

            var options = {
                chart: {
                    map: 'countries/us/us-all',
                    width: 800,
                    height: 600,
                    marginTop: 40,
                },
                exporting: {
                    buttons: {
                        contextButton: {
                            menuItems: ['viewFullscreen', 'printChart', 'separator', 'downloadPNG', 'downloadJPEG', 'downloadPDF', 'downloadSVG']
                        }
                    },
                    enabled: true
                },

                title: {
                    text: 'United States',
                    align: 'center',
                    style: {
                        color: '#333333',
                        fontSize: '16px',
                        lineHeight: '22px',
                        fontWeight: '500',
                        fontFamily: 'Noto Sans, Roboto',
                    },
                    enabled: true,
                },
                legend: {
                    title: {
                        text: 'Percentage of Establishments (%)',
                        style: {
                            color: '#333333',
                            fontSize: '14px',
                            lineHeight: '18px',
                            fontWeight: 'normal',
                        },
                    },
                    borderWidth: 0,
                    backgroundColor: 'rgba(255,255,255,0.85)',
                    floating: true,
                    layout: 'horizontal',
                    verticalAlign: 'bottom',
                    y: 0,
                    align: 'right',
                },
                credits: {
                    enabled: false
                },

                tooltip: {
                    valueDecimals: 1,
                    backgroundColor: '#FFFFFF',
                    borderColor: '#AAA',
                    borderRadius: 10,
                    style: {
                        padding: 0,
                    },
                    useHTML: true,
                    formatter: function() {
                        //console.log(this);
                        return '<div class="map-tooltip">' +
                            '<span style="color:' + this.point.color + '">\u25CF</span><br>' +
                            '<div class="label">' + this.point.name + '<br>' + this.point.value + '%' + '</div>' +
                            '</div>';
                    },
                },
                plotOptions: {
                    map: {
                        borderColor: 'white',
                        borderWidth: 0.2,
                        joinBy: ['name', 'name'],
                        dataLabels: {
                            enabled: true,
                            style: {
                                color: '#002F65',
                                fontSize: '14px',
                                fontWeight: 'normal',
                                textOutline: '1px #FFFFFF'
                            },
                            formatter: function() {
                                var max = 6,
                                    color = this.point.value < max ? 'black' : 'white';
                                //console.log(this);  

                                if (this.point.name == 'Norfolk Island' || this.point.name == 'Yukon' || this.point.name == 'Nunavut' || this.point.name == undefined || this.point.name == 'Bounty Islands' || this.point.name == 'The Snares') {

                                } else if (this.series.mapTitle == 'Australia') {
                                    if (this.point['hc-a2'] == 'CT') {
                                        return '<span style="color: black; font-weight:bold;font-size:12px;">ACT</span><br>';
                                    } else if (this.point['hc-a2'] == 'NS') {
                                        return '<span style="color: black; font-weight:bold;font-size:12px; ">NSW</span><br>';
                                    } else if (this.point['hc-a2'] == 'QL') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">QLD</span><br>';
                                    } else if (this.point['hc-a2'] == 'TS') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">TAS</span><br>';
                                    } else if (this.point['hc-a2'] == 'VI') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">VIC</span><br>';
                                    } else {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">' + this.point['hc-a2'] + '</span><br>';
                                    }
                                } else if (this.series.mapMap.Dublin) {
                                    if (this.key == 'Mid-East') {
                                        return '<span style="color: black; font-weight:bold;font-size:12px;">ME</span><br>';
                                    } else if (this.key == 'South-West') {
                                        return '<span style="color: black; font-weight:bold;font-size:12px; ">SW</span><br>';
                                    } else if (this.key == 'South-East') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">SE</span><br>';
                                    } else if (this.key == 'Midland') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">MD</span><br>';
                                    } else if (this.key == 'Mid-West') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">MW</span><br>';
                                    } else if (this.key == 'Border') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">BO</span><br>';
                                    } else if (this.key == 'West') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">W</span><br>';
                                    } else if (this.key == 'Dublin') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">DU</span><br>';
                                    } else {
                                        return '';
                                    }
                                } else if (this.series.mapMap.Scotland) {
                                    if (this.key == 'Scotland') {
                                        return '<span style="color: black; font-weight:bold;font-size:12px;">SCT</span><br>';
                                    } else if (this.key == 'Wales') {
                                        return '<span style="color: black; font-weight:bold;font-size:12px; ">WAL</span><br>';
                                    } else if (this.key == 'East Midlands') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">EMD</span><br>';
                                    } else if (this.key == 'South West') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">SW</span><br>';
                                    } else if (this.key == 'Northern Ireland') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">NIR</span><br>';
                                    } else if (this.key == 'Yorkshire') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">YKS</span><br>';
                                    } else if (this.key == 'North East') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">NE</span><br>';
                                    } else if (this.key == 'North West') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">NW</span><br>';
                                    } else if (this.key == 'South East') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">SE</span><br>';
                                    } else if (this.key == 'West Midlands') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">WMD</span><br>';
                                    } else if (this.key == 'East of England') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">‎UKH</span><br>';
                                    } else if (this.key == 'London') {
                                        return '<span style="color: black; font-weight:bold; font-size:12px; ">‎LDN</span><br>';
                                    } else {
                                        return '';
                                    }
                                } else if (this.series.mapTitle == 'United States of America' || this.series.mapTitle == 'Canada' || this.series.mapTitle == 'China' || this.series.mapTitle == 'New Zealand' || this.series.mapTitle == 'Germany') {
                                    try {
                                        return '<span style="color: black; font - weight:bold; font - size:12px; ">' + this.point.properties['hc-a2'] + '</span><br>';
                                    } catch (err) {
                                        if (this.point.name == 'Tibet') {
                                            return '<span style="color: black; font - weight:bold; font - size:12px; ">TB</span><br>';
                                        }
                                        if (this.point.name == 'Inner Mongolia') {
                                            return '<span style="color: black; font - weight:bold; font - size:12px; ">NM</span><br>';
                                        } else {
                                            console.log('not rendering', this.point.name);
                                        }
                                    }
                                } else {
                                    return '<span style="color: black; font - weight:bold; font - size:12px; ">' + this.point.name + '</span><br>';
                                }
                            },
                        },
                    },
                },
            };

            if (options.yAxis && options.yAxis.length === 1) options.yAxis = options.yAxis[0];
            if (options.xAxis && options.xAxis.length === 1) options.xAxis = options.xAxis[0];
            if (options.zAxis && options.zAxis.length === 1) options.zAxis = options.zAxis[0];

            Highcharts.merge(true, options, optionsNew);

            if (options && (options.lang || options.global)) {

                Highcharts.setOptions({
                    global: options.global || {},
                    lang: options.lang || {}
                });

            }
            if (1 == 2) {
                Highcharts.setOptions({
                    lang: {
                        decimalPoint: ',',
                        thousandsSep: '.'
                    }
                });
            }

            var chart = new Highcharts.mapChart('vis-BusinessConcentration', options);

            if (chart) {
                if (chart.options.exporting.buttons.contextButton.menuItems.length == 3) {
                    chart.options.exporting.buttons.contextButton.menuItems[2].text = 'View Data'.toUpperCase();
                }
            }



        }
    }

}());

1 Ответ

0 голосов
/ 10 апреля 2020

Рабочая демонстрация с вашим упрощенным кодом: http://jsfiddle.net/BlackLabel/54kc3epq/

Все, что нужно сделать, это:

  1. Вставить пользовательский скрипт карты в HTML

  2. Копировать переменную mapData и поправку dataLabels:

       mapData = Highcharts.geojson(Highcharts.maps['countries/us/custom/us-small']);
    
        $.each(mapData, function() {
            var path = this.path,
                copy = {
                   path: path
                };
    
        // This point has a square legend to the right
        if (path[1] === 9727) {
    
        // Identify the box
        Highcharts.seriesTypes.map.prototype.getBox.call({}, [copy]);
    
        // Place the center of the data label in the center of the point legend box
        this.middleX = ((path[1] + path[4]) / 2 - copy._minX) / (copy._maxX - copy._minX);
        this.middleY = ((path[2] + path[7]) / 2 - copy._minY) / (copy._maxY - copy._minY);
         }
    
        // Tag it for joining
        this.ucName = this.name.toUpperCase();
    });
    
  3. Определить mapData в конфигурации серии.

Далее время, когда вам понадобится помощь, пожалуйста, упростите код из ненужных частей, не связанных с проблемой, насколько это возможно. Это облегчит поиск решения или даже прояснит ситуацию, которая позволит найти его самостоятельно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...