Geochart实现各国自定义唯一颜色填充及对应图例展示需求
实现Geochart自定义国家颜色及对应图例
我明白你想要的效果——给每个指定国家分配唯一颜色,并且在地图下方显示清晰的国家-颜色对应图例。原代码里的colors数组已经能给国家分配颜色,但默认的Geochart图例是基于数值范围的,没法直接显示单个国家的对应关系,所以我们需要手动构建自定义图例。
下面是修改后的完整代码,直接就能实现你要的效果:
<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'], 'mapsApiKey': 'AIzaSyBSJt5Ja1t7FFBGb_CZYKzFbTOCIX-nTWs' }); google.charts.setOnLoadCallback(drawRegionsMap); function drawRegionsMap() { // 统一管理国家代码、名称和对应颜色,避免数据和颜色错位 const countryColorMap = [ ['IN', 'India', 'red'], ['US', 'United States', 'green'], ['AT', 'Austria', 'orange'], ['CA', 'Canada', 'blue'], ['CN', 'China', 'yellow'] ]; // 生成图表需要的数据源 const chartData = [['Country', 'value']]; const colors = []; countryColorMap.forEach(item => { chartData.push([item[0], 1]); // 这里数值用1即可,因为我们是按行分配颜色,数值不影响 colors.push(item[2]); }); const data = google.visualization.arrayToDataTable(chartData); const options = { colors: colors, legend: 'none' // 关闭默认图例,我们用自定义的 }; const chart = new google.visualization.GeoChart(document.getElementById('geochart-colors')); chart.draw(data, options); // 生成自定义图例 const legendContainer = document.createElement('div'); legendContainer.style.marginTop = '20px'; legendContainer.style.display = 'flex'; legendContainer.style.flexWrap = 'wrap'; legendContainer.style.gap = '15px'; countryColorMap.forEach(item => { const legendItem = document.createElement('div'); legendItem.style.display = 'flex'; legendItem.style.alignItems = 'center'; legendItem.style.gap = '5px'; // 颜色块 const colorBlock = document.createElement('span'); colorBlock.style.width = '20px'; colorBlock.style.height = '20px'; colorBlock.style.backgroundColor = item[2]; colorBlock.style.border = '1px solid #ccc'; // 国家名称 const countryName = document.createElement('span'); countryName.textContent = item[1]; legendItem.appendChild(colorBlock); legendItem.appendChild(countryName); legendContainer.appendChild(legendItem); }); // 把图例添加到地图下方 document.getElementById('geochart-colors').after(legendContainer); }; </script> </head> <body> <div id="geochart-colors" style="width: 700px; height: 433px;"></div> </body> </html>
关键修改说明:
- 统一管理映射关系:创建
countryColorMap数组,把国家代码、名称、颜色放在一起,这样后续修改或新增国家时,数据和颜色不会对应错误。 - 调整图表数值:因为我们是按数据行的顺序分配颜色,数值可以统一设为1,不影响颜色分配,也避免默认图例按数值分组。
- 关闭默认图例:在
options里设置legend: 'none',避免默认图例干扰。 - 手动生成自定义图例:通过DOM操作创建每个图例项,包含颜色块和国家名称,用CSS调整样式,最后把图例容器插入到地图容器的后面。
这样就能实现你想要的:每个国家对应指定的唯一颜色,地图下方显示清晰的国家-颜色图例。
内容的提问来源于stack exchange,提问作者Coder
相关产品推荐
相关产品推荐

