Search code examples
google-mapsgoogle-maps-api-3google-visualizationgoogle-maps-api-2

Geochart fill countries with unique colors and show country names with its color as legends


i need to fill each countries with unique color specified in a list and display country name and its color as legend below of the map.as shown in images attached with this.any help will be appreciated.

enter image description here enter image description here

    <html>
     <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
        google.charts.load('current', {
            'packages': ['geochart'],
            // Note: you will need to get a mapsApiKey for your project.
            // See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
            'mapsApiKey': 'AIzaSyBSJt5Ja1t7FFBGb_CZYKzFbTOCIX-nTWs&callback'
        });
        google.charts.setOnLoadCallback(drawRegionsMap);



        function drawRegionsMap() {
            var data = google.visualization.arrayToDataTable([
                ['Country', 'value'],
                ['IN', 28],
                ['US', 40],
                ['AT', 15],
                ['CA', 10],
                ['CN', 5]

            ]);

            var options = {              
                colors: ['red', 'green', 'orange', 'blue', 'yellow']


            };

            var chart = new google.visualization.GeoChart(document.getElementById('geochart-colors'));
            chart.draw(data, options);                
        };
    </script>
</head>
<body>
    <div id="geochart-colors" style="width: 700px; height: 433px;"></div>
</body>
</html>

Solution

  • in order to assign a unique color to each country using GeoChart,
    each country will need a unique value

    the colorAxis allows you to assign a color to a specific value,
    using the colorAxis.colors and colorAxis.values options

    the first value in values will be assigned the first color in colors,
    in the following example, 0 = 'red', 1 = 'green', etc...

    colorAxis: {
      colors: ['red', 'green', 'orange', 'blue', 'yellow'],
      values: [0, 1, 2, 3, 4]
    }
    

    to ensure a unique value for each country,
    change the country's value to the row index,
    and set the country's actual value as the formatted value of the data table cell
    this will allow the country's actual value to be seen on hover

    for (var i = 0; i < data.getNumberOfRows(); i++) {
      var countryValue = data.getValue(i, 1);
      data.setValue(i, 1, i);
      data.setFormattedValue(i, 1, countryValue + '%');
    }
    

    you will need the same number of colors as there are rows in the data table

    as for a legend, you'll have to build manually,
    see following working snippet...

    google.charts.load('current', {
      packages: ['geochart'],
      mapsApiKey: 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
    }).then(function () {
      var data = google.visualization.arrayToDataTable([
        ['Country', 'value'],
        ['IN', 28],
        ['US', 40],
        ['AT', 15],
        ['CA', 10],
        ['CN', 5]
      ]);
    
      for (var i = 0; i < data.getNumberOfRows(); i++) {
        var countryValue = data.getValue(i, 1);
        data.setValue(i, 1, i);
        data.setFormattedValue(i, 1, countryValue + '%');
      }
    
      var options = {
        colorAxis: {
          colors: ['red', 'green', 'orange', 'blue', 'yellow'],
          values: [0, 1, 2, 3, 4]
        },
        legend: 'none'
      };
    
      var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
    
      google.visualization.events.addListener(chart, 'ready', function () {
        var legend = document.getElementById('legend_div');
        legend.innerHTML = '';
    
        for (var i = 0; i < data.getNumberOfRows(); i++) {
          addLegendMarker({
            color: options.colorAxis.colors[i],
            label: data.getValue(i, 0) + ' ' + data.getFormattedValue(i, 1)
          });
        }
    
        function addLegendMarker(markerProps) {
          var legendMarker = document.getElementById('template-legend-marker').innerHTML;
          for (var handle in markerProps) {
            if (markerProps.hasOwnProperty(handle)) {
              legendMarker = legendMarker.replace('{{' + handle + '}}', markerProps[handle]);
            }
          }
          legend.insertAdjacentHTML('beforeEnd', legendMarker);
        }
      });
    
      window.addEventListener('resize', function () {
        chart.draw(data, options);
      });
      chart.draw(data, options);
    });
    html, body {
      height: 100%;
      margin: 0px 0px 0px 0px;
      overflow: hidden;
      padding: 0px 0px 0px 0px;
    }
    
    .chart {
      height: 100%;
    }
    
    .legend {
      bottom: 0px;
      position: absolute;
      text-align: center;
      width: 100%;
      z-index: 1000;
    }
    
    .legend-marker {
      display: inline-block;
      padding: 6px 6px 6px 6px;
    }
    
    .legend-marker-color {
      border-radius: 25%;
      display: inline-block;
      height: 16px;
      width: 16px;
    }
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div class="legend" id="legend_div"></div>
    <div class="chart" id="chart_div"></div>
    
    <script id="template-legend-marker" type="text/html">
      <div class="legend-marker">
        <span class="legend-marker-color" style="background-color: {{color}}">&nbsp;</span>
        <span>{{label}}</span>
      </div>
    </script>