使用Echart.js和world.js实现世界地图完整代码

 更新时间:2026年03月17日 10:32:59   作者:Laker 23  
world.js是一个地图数据处理插件,能够将地理信息转换为ECharts可识别的数据格式,使得开发者能够在图表中显示地图并进行地理数据的展示,这篇文章主要介绍了使用Echart.js和world.js实现世界地图的相关资料,需要的朋友可以参考下
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>世界地图 - 可交互数据可视化</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts/map/js/world.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f0f2f5;
        }

        .container {
            width: 100%;
            height: 100vh;
            display: flex;
            flex-direction: column;
            padding: 20px;
            box-sizing: border-box;
        }

        .header {
            text-align: center;
            margin-bottom: 20px;
        }

        .header h1 {
            color: #333;
            margin: 0;
        }

        .map-container {
            flex: 1;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            overflow: hidden;
        }

        #worldMap {
            width: 100%;
            height: 100%;
            min-height: 600px;
        }

        .info-panel {
            position: absolute;
            top: 50%;
            right: 20px;
            transform: translateY(-50%);
            background: rgba(255, 255, 255, 0.9);
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            max-width: 300px;
            display: none;
        }

        .info-panel.active {
            display: block;
        }

        .info-panel h3 {
            margin-top: 0;
            color: #333;
        }

        .info-panel p {
            margin: 10px 0;
            color: #666;
            line-height: 1.6;
        }

        .controls {
            margin-top: 20px;
            text-align: center;
        }

        .controls button {
            margin: 0 10px;
            padding: 8px 20px;
            background-color: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        .controls button:hover {
            background-color: #40a9ff;
        }

        .controls button:active {
            background-color: #096dd9;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <h1>世界地图数据可视化</h1>
        </div>
        <div class="map-container">
            <div id="worldMap"></div>
        </div>
        <div class="controls">
            <button id="showPopulation">显示人口数据</button>
            <button id="showGDP">显示GDP数据</button>
            <button id="showArea">显示面积数据</button>
            <button id="resetMap">重置地图</button>
        </div>
    </div>
    <div id="countryInfo" class="info-panel">
        <h3 id="countryName"></h3>
        <p id="countryDetail"></p>
    </div>

    <script>
        // 初始化地图
        const chartDom = document.getElementById('worldMap');
        const myChart = echarts.init(chartDom);

        // 模拟数据 - 实际项目中可替换为真实数据
        const populationData = [
            { name: 'China', value: 1402, color: '#000', backgroundColor: '#fff' },
            { name: 'India', value: 1366, color: '#fa8c16' },
            { name: 'United States', value: 331, color: '#52c41a' },
            { name: 'Indonesia', value: 273, color: '#1890ff' },
            { name: 'Pakistan', value: 225, color: '#722ed1' },
            { name: 'Brazil', value: 213, color: '#eb2f96' },
            { name: 'Nigeria', value: 206, color: '#faad14' },
            { name: 'Bangladesh', value: 165, color: '#13c2c2' },
            { name: 'Russia', value: 146, color: '#52c41a' },
            { name: 'Mexico', value: 129, color: '#722ed1' }
        ];

        const gdpData = [
            { name: 'United States', value: 25.46, color: '#000' },
            { name: 'China', value: 17.92, color: '#000' },
            { name: 'Japan', value: 4.23, color: '#52c41a' },
            { name: 'Germany', value: 4.07, color: '#1890ff' },
            { name: 'India', value: 3.39, color: '#722ed1' },
            { name: 'United Kingdom', value: 3.07, color: '#eb2f96' },
            { name: 'France', value: 2.78, color: '#faad14' },
            { name: 'Italy', value: 2.08, color: '#13c2c2' },
            { name: 'Canada', value: 2.0, color: '#52c41a' },
            { name: 'South Korea', value: 1.81, color: '#722ed1' }
        ];

        const areaData = [
            { name: 'Russia', value: 17.1, color: '#ff4d4f' },
            { name: 'Canada', value: 9.98, color: '#fa8c16' },
            { name: 'China', value: 9.6, color: '#fff' },
            { name: 'United States', value: 9.37, color: '#1890ff' },
            { name: 'Brazil', value: 8.51, color: '#722ed1' },
            { name: 'Australia', value: 7.69, color: '#eb2f96' },
            { name: 'India', value: 3.28, color: '#faad14' },
            { name: 'Argentina', value: 2.78, color: '#13c2c2' },
            { name: 'Kazakhstan', value: 2.72, color: '#52c41a' },
            { name: 'Algeria', value: 2.38, color: '#722ed1' }
        ];

        // 国家详细信息
        const countryDetails = {
            'China': '中国是世界上人口最多的国家,位于亚洲东部。首都北京,国土面积约960万平方公里。',
            'United States': '美国是世界上最大的经济体,位于北美洲。首都华盛顿,国土面积约937万平方公里。',
            'India': '印度是世界第二人口大国,位于南亚次大陆。首都新德里,国土面积约328万平方公里。',
            'Japan': '日本是一个岛国,位于东亚。首都东京,是世界第三大经济体。',
            'Germany': '德国位于欧洲中部,是欧洲最大的经济体。首都柏林。',
            'Russia': '俄罗斯是世界上面积最大的国家,地跨欧亚两洲。首都莫斯科。',
            'Brazil': '巴西是南美洲最大的国家,以足球和热带雨林闻名。首都巴西利亚。'
        };

        // 基础配置
        let option = {
            title: {
                text: '世界地图数据可视化',
                left: 'center',
                textStyle: {
                    color: '#333',
                    fontSize: 18
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: function (params) {
                    if (params.value) {
                        return params.name + '
' + getCurrentDataType() + ': ' + params.value;
                    }
                    return params.name;
                }
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                show: false
            },
            visualMap: {
                type: 'continuous',
                min: 0,
                max: 1500,
                left: 'left',
                top: 'bottom',
                text: ['高', '低'],
                calculable: true,
                inRange: {
                    color: ['#e6f7ff', '#1890ff']
                }
            },
            series: [
                {
                    name: '数据',
                    type: 'map',
                    map: 'world',
                    roam: true,
                    emphasis: {
                        label: {
                            show: true,
                            color: '#333',
                            fontSize: 12
                        },
                        itemStyle: {
                            areaColor: '#f0f9ff',
                            borderColor: '#1890ff',
                            borderWidth: 2
                        }
                    },
                    select: {
                        itemStyle: {
                            areaColor: '#000'
                        },
                        label: {
                            show: true,
                            color: '#fff'
                        },
                        color: '#fff'
                    },
                    data: populationData
                }
            ]
        };

        let currentDataType = '人口(百万)';
        let currentData = populationData;

        // 获取当前数据类型文本
        function getCurrentDataType() {
            return currentDataType;
        }

        // 更新地图数据
        function updateMapData(data, type, maxValue) {
            currentData = data;
            currentDataType = type;

            option.visualMap.max = maxValue;
            option.series[0].data = data;
            option.title.text = '世界地图 - ' + type + '数据可视化';
            myChart.setOption(option);
        }

        // 重置地图
        function resetMap() {
            myChart.dispatchAction({
                type: 'restore'
            });
            document.getElementById('countryInfo').classList.remove('active');
        }

        // 绑定点击事件
        myChart.on('click', function (params) {
            const countryInfo = document.getElementById('countryInfo');
            const countryName = document.getElementById('countryName');
            const countryDetail = document.getElementById('countryDetail');

            countryName.textContent = params.name;
            countryDetail.textContent = countryDetails[params.name] || '暂无详细信息';
            countryInfo.classList.add('active');
        });

        // 点击空白区域关闭信息面板
        myChart.getZr().on('click', function () {
            document.getElementById('countryInfo').classList.remove('active');
        });

        // 绑定按钮事件
        document.getElementById('showPopulation').addEventListener('click', function () {
            updateMapData(populationData, '人口(百万)', 1500);
        });

        document.getElementById('showGDP').addEventListener('click', function () {
            updateMapData(gdpData, 'GDP(万亿美元)', 30);
        });

        document.getElementById('showArea').addEventListener('click', function () {
            updateMapData(areaData, '面积(百万平方公里)', 20);
        });

        document.getElementById('resetMap').addEventListener('click', resetMap);

        // 响应式调整
        window.addEventListener('resize', function () {
            myChart.resize();
        });

        // 设置配置项
        myChart.setOption(option);
    </script>
</body>

</html>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>世界地图-大洲高亮</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts/map/js/world.js"></script>
    <style>
        #worldMap {
            width: 100%;
            height: 100vh;
            background: #f0f2f5;
        }
    </style>
</head>

<body>
    <div id="worldMap"></div>

    <script>
        // 完整的国家到大洲映射
        const countryToContinent = {
            'China': '亚洲', 'Japan': '亚洲', 'South Korea': '亚洲', 'India': '亚洲',
            'Indonesia': '亚洲', 'Thailand': '亚洲', 'Vietnam': '亚洲', 'Malaysia': '亚洲',
            'Germany': '欧洲', 'France': '欧洲', 'United Kingdom': '欧洲', 'Italy': '欧洲',
            'Spain': '欧洲', 'Russia': '欧洲', 'United States': '北美洲', 'Canada': '北美洲',
            'Mexico': '北美洲', 'Brazil': '南美洲', 'Argentina': '南美洲', 'Egypt': '非洲',
            'South Africa': '非洲', 'Australia': '大洋洲', 'New Zealand': '大洋洲',
            // 此处应包含所有200+国家地区的完整映射
            // 为节省篇幅已简化,实际使用时需补全
        };

        // 生成大洲国家列表
        const continentMap = {};
        Object.entries(countryToContinent).forEach(([country, continent]) => {
            if (!continentMap[continent]) {
                continentMap[continent] = [];
            }
            continentMap[continent].push(country);
        });

        const chart = echarts.init(document.getElementById('worldMap'));

        const option = {
            tooltip: {
                trigger: 'item',
                formatter: params => {
                    const continent = countryToContinent[params.name] || '未知大洲';
                    return `<div style="padding:5px">${continent}</div>`;
                }
            },
            series: [{
                type: 'map',
                map: 'world',
                roam: true,
                itemStyle: {
                    normal: {
                        areaColor: '#E0E0E0',
                        borderColor: '#FFF',
                        borderWidth: 0.5
                    }
                },
                emphasis: {
                    disabled: true // 禁用默认高亮
                }
            }]
        };

        // 事件处理
        chart.on('mouseover', { seriesIndex: 0 }, (e) => {
            const continent = countryToContinent[e.name];
            if (continent && continentMap[continent]) {
                chart.setOption({
                    series: [{
                        regions: continentMap[continent].map(country => ({
                            name: country,
                            itemStyle: {
                                areaColor: '#ff0000',
                                borderColor: '#333',
                                borderWidth: 1
                            }
                        }))
                    }]
                });
            }
        });

        chart.on('globalout', () => {
            chart.setOption({
                series: [{
                    regions: []
                }]
            });
        });

        chart.setOption(option);
        window.addEventListener('resize', chart.resize);
    </script>
</body>

</html>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>世界地图 - 大洲联动高亮</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="external nofollow"  rel="stylesheet">
    <!-- 引入ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>

    <!-- 配置Tailwind自定义颜色 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        accent: '#722ED1',
                        neutral: '#1F2937',
                        'neutral-light': '#F3F4F6',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .map-container {
                height: 70vh;
                min-height: 500px;
            }
            .card-shadow {
                box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.02);
            }
            .fade-in {
                animation: fadeIn 0.5s ease-in-out;
            }
            @keyframes fadeIn {
                from { opacity: 0; }
                to { opacity: 1; }
            }
        }
    </style>
</head>

<body class="font-inter bg-gray-50 text-neutral">
    <!-- 页面头部 -->
    <header class="bg-white shadow-md py-4 px-6 md:px-12">
        <div class="container mx-auto flex flex-col md:flex-row justify-between items-center">
            <div class="flex items-center space-x-2 mb-4 md:mb-0">
                <i class="fa fa-globe text-primary text-2xl"></i>
                <h1 class="text-xl md:text-2xl font-bold text-neutral">世界地图可视化</h1>
            </div>
            <div class="text-sm text-gray-500">
                <p>交互提示:鼠标悬停或点击国家,查看所属大洲联动高亮效果</p>
            </div>
        </div>
    </header>

    <!-- 主要内容区 -->
    <main class="container mx-auto p-6 md:p-12">
        <!-- 控制面板 -->
        <div class="bg-white rounded-lg p-4 mb-6 card-shadow">
            <div class="flex flex-wrap gap-4">
                <div class="flex items-center">
                    <span class="w-4 h-4 rounded-full bg-green-400 inline-block mr-2"></span>
                    <span class="text-sm">亚洲</span>
                </div>
                <div class="flex items-center">
                    <span class="w-4 h-4 rounded-full bg-yellow-400 inline-block mr-2"></span>
                    <span class="text-sm">非洲</span>
                </div>
                <div class="flex items-center">
                    <span class="w-4 h-4 rounded-full bg-blue-400 inline-block mr-2"></span>
                    <span class="text-sm">欧洲</span>
                </div>
                <div class="flex items-center">
                    <span class="w-4 h-4 rounded-full bg-red-400 inline-block mr-2"></span>
                    <span class="text-sm">北美洲</span>
                </div>
                <div class="flex items-center">
                    <span class="w-4 h-4 rounded-full bg-purple-400 inline-block mr-2"></span>
                    <span class="text-sm">南美洲</span>
                </div>
                <div class="flex items-center">
                    <span class="w-4 h-4 rounded-full bg-pink-400 inline-block mr-2"></span>
                    <span class="text-sm">大洋洲</span>
                </div>
                <div class="flex items-center">
                    <span class="w-4 h-4 rounded-full bg-gray-400 inline-block mr-2"></span>
                    <span class="text-sm">南极洲</span>
                </div>
                <button id="reset-btn"
                    class="ml-auto px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors text-sm flex items-center">
                    <i class="fa fa-refresh mr-1"></i> 重置视图
                </button>
            </div>
        </div>

        <!-- 地图容器 -->
        <div class="bg-white rounded-lg shadow-lg overflow-hidden">
            <div id="map-loading" class="w-full map-container flex flex-col items-center justify-center text-gray-500">
                <i class="fa fa-spinner fa-spin mr-2 text-2xl mb-4"></i>
                <p>正在加载地图数据...</p>
            </div>
            <div id="map" class="w-full map-container hidden"></div>
            <div id="map-error"
                class="w-full map-container flex flex-col items-center justify-center text-red-500 p-6 hidden">
                <i class="fa fa-exclamation-circle mr-2 text-2xl mb-4"></i>
                <p class="text-center mb-4">地图加载失败</p>
                <button id="retry-btn"
                    class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors text-sm flex items-center">
                    <i class="fa fa-refresh mr-1"></i> 重试加载
                </button>
            </div>
        </div>

        <!-- 信息面板 -->
        <div id="info-panel" class="mt-6 bg-white rounded-lg p-6 card-shadow hidden fade-in">
            <h2 class="text-lg font-semibold mb-4 flex items-center">
                <i class="fa fa-info-circle text-primary mr-2"></i>
                <span id="info-title">区域信息</span>
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <p class="text-sm text-gray-500 mb-1">国家/地区</p>
                    <p id="country-name" class="font-medium">-</p>
                </div>
                <div>
                    <p class="text-sm text-gray-500 mb-1">所属大洲</p>
                    <p id="continent-name" class="font-medium">-</p>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-neutral text-white py-6 px-6 mt-12">
        <div class="container mx-auto text-center text-sm">
            <p>世界地图可视化演示 | 使用 ECharts.js 实现</p>
        </div>
    </footer>

    <script>
        // 大洲与数值映射(用于visualMap颜色映射)
        const continentValue = {
            '亚洲': 1,
            '非洲': 2,
            '欧洲': 3,
            '北美洲': 4,
            '南美洲': 5,
            '大洋洲': 6,
            '南极洲': 7
        };

        // 大洲颜色映射
        const continentColors = {
            '亚洲': '#86e07a',     // 绿色
            '非洲': '#f9e378',     // 黄色
            '欧洲': '#7cb5ec',     // 蓝色
            '北美洲': '#f77976',   // 红色
            '南美洲': '#c293e2',   // 紫色
            '大洋洲': '#f7a3c4',   // 粉色
            '南极洲': '#d3d3d3'    // 灰色
        };

        // 大洲高亮颜色映射
        const highlightColors = {
            '亚洲': '#52c41a',     // 深绿色
            '非洲': '#faad14',     // 深黄色
            '欧洲': '#1890ff',     // 深蓝色
            '北美洲': '#f5222d',   // 深红色
            '南美洲': '#722ed1',   // 深紫色
            '大洋洲': '#eb2f96',   // 深粉色
            '南极洲': '#8c8c8c'    // 深灰色
        };

        // 国家与大洲的映射关系
        const countryToContinent = {
            // 亚洲国家
            'China': '亚洲',
            'Japan': '亚洲',
            'South Korea': '亚洲',
            'India': '亚洲',
            'Indonesia': '亚洲',
            'Saudi Arabia': '亚洲',
            'Turkey': '亚洲',

            // 非洲国家
            'South Africa': '非洲',
            'Nigeria': '非洲',
            'Egypt': '非洲',
            'Kenya': '非洲',

            // 欧洲国家
            'Germany': '欧洲',
            'France': '欧洲',
            'United Kingdom': '欧洲',
            'Russia': '欧洲',
            'Italy': '欧洲',

            // 北美洲国家
            'United States of America': '北美洲',
            'United States': '北美洲',
            'Canada': '北美洲',
            'Mexico': '北美洲',
            'Cuba': '北美洲',

            // 南美洲国家
            'Brazil': '南美洲',
            'Argentina': '南美洲',
            'Chile': '南美洲',

            // 大洋洲国家
            'Australia': '大洋洲',
            'New Zealand': '大洋洲',

            // 南极洲
            'Antarctica': '南极洲'
        };

        // 初始化图表
        let chart;
        // 存储所有国家数据
        let allCountries = [];
        let mapLoading = false;

        // 加载世界地图数据
        function loadMapData() {
            if (mapLoading) return;

            mapLoading = true;
            document.getElementById('map-loading').classList.remove('hidden');
            document.getElementById('map').classList.add('hidden');
            document.getElementById('map-error').classList.add('hidden');

            // 多数据源尝试
            const mapSources = [
                'https://cdn.jsdelivr.net/npm/echarts/map/js/world.js',
                'https://unpkg.com/echarts@5.4.3/map/js/world.js'
            ];

            const loadWithSource = (sourceIndex) => {
                if (sourceIndex >= mapSources.length) {
                    console.error('所有地图数据源加载失败');
                    mapLoading = false;
                    document.getElementById('map-loading').classList.add('hidden');
                    document.getElementById('map-error').classList.remove('hidden');
                    return;
                }

                const script = document.createElement('script');
                script.src = mapSources[sourceIndex];

                script.onload = function () {
                    console.log(`地图数据从 ${mapSources[sourceIndex]} 加载成功`);
                    mapLoading = false;
                    initMap();
                };

                script.onerror = function () {
                    console.error(`地图数据从 ${mapSources[sourceIndex]} 加载失败,尝试下一个`);
                    document.body.removeChild(script);
                    loadWithSource(sourceIndex + 1);
                };

                setTimeout(() => {
                    if (mapLoading) {
                        console.error(`地图数据加载超时`);
                        document.body.removeChild(script);
                        loadWithSource(sourceIndex + 1);
                    }
                }, 8000);

                document.body.appendChild(script);
            };

            loadWithSource(0);
        }

        // 获取国家数据
        function getCountryData() {
            const data = [];

            Object.keys(countryToContinent).forEach(country => {
                const continent = countryToContinent[country];
                data.push({
                    name: country,
                    value: continentValue[continent],
                    continent: continent,
                    itemStyle: {
                        color: continentColors[continent]
                    },
                    emphasis: {
                        itemStyle: {
                            color: highlightColors[continent]
                        }
                    }
                });
            });

            allCountries = data;
            return data;
        }

        // 获取指定大洲的所有国家
        function getCountriesInContinent(continent) {
            return allCountries
                .filter(country => country.continent === continent)
                .map(country => country.name);
        }

        // 初始化地图
        function initMap() {
            if (typeof echarts === 'undefined' || !echarts.getMap('world')) {
                console.error('ECharts或地图数据未正确加载');
                document.getElementById('map-loading').classList.add('hidden');
                document.getElementById('map-error').classList.remove('hidden');
                mapLoading = false;
                return;
            }

            document.getElementById('map-loading').classList.add('hidden');
            document.getElementById('map').classList.remove('hidden');

            chart = echarts.init(document.getElementById('map'));

            // ECharts配置项
            const option = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        if (!params || !params.data) {
                            return `${params.name}
所属大洲: 未定义`;
                        }
                        return `${params.name}
所属大洲: ${params.data.continent || '未知'}`;
                    }
                },

                series: [
                    {
                        name: '世界地图',
                        type: 'map',
                        mapType: 'world',
                        roam: true,
                        zoom: 1.2,
                        label: {
                            show: false
                        },
                        itemStyle: {
                            borderColor: '#fff',
                            borderWidth: 0.5
                        },
                        // 关键修改:设置选中模式
                        selectedMode: 'multiple',
                        // 选中样式配置 - 提高优先级
                        select: {
                            itemStyle: {
                                // 使用更明显的颜色差异
                                color: function (params) {
                                    const color = highlightColors[params.data.continent];
                                    console.log(`选中 ${params.name} (${params.data.continent}) 颜色: ${color}`);
                                    return color || '#ffd700';
                                },
                                // 增加选中状态的视觉效果
                                borderColor: '#fff',
                                borderWidth: 2,
                                shadowBlur: 10,
                                shadowColor: 'rgba(0, 0, 0, 0.3)'
                            },
                            label: {
                                show: true,
                                color: '#fff',
                                fontWeight: 'bold',
                                shadowBlur: 5,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        // 鼠标悬停样式
                        emphasis: {
                            label: {
                                show: true,
                                color: '#333',
                                fontWeight: 'bold'
                            },
                            itemStyle: {
                                color: function (params) {
                                    return highlightColors[params.data.continent] || '#ccc';
                                }
                            }
                        },
                        data: getCountryData()
                    }
                ]
            };

            chart.setOption(option);
            bindEvents();
        }

        // 高亮指定大洲的所有国家
        function highlightContinent(continent) {
            if (!chart) return;

            console.log(`高亮大洲: ${continent}`);

            // 重置所有选中状态
            // chart.dispatchAction({
            //     type: 'unselect',
            //     seriesIndex: 0
            // });

            if (!continent) return;

            const countries = getCountriesInContinent(continent);
            console.log(`需要高亮的国家:`, countries);

            // 触发选中事件,显式设置选中状态
            countries.forEach(country => {
                chart.dispatchAction({
                    type: 'select',
                    seriesIndex: 0,
                    name: country
                });
            });
        }

        // 显示国家信息
        function showCountryInfo(countryName) {
            const continent = countryToContinent[countryName] || '未知';
            document.getElementById('country-name').textContent = countryName;
            document.getElementById('continent-name').textContent = continent;
            document.getElementById('info-title').textContent = `${countryName} - 区域信息`;
            document.getElementById('info-panel').classList.remove('hidden');
        }

        // 重置地图
        function resetMap() {
            if (chart) {
                chart.dispatchAction({
                    type: 'unselect',
                    seriesIndex: 0
                });
                document.getElementById('info-panel').classList.add('hidden');
            }
        }

        // 绑定事件
        function bindEvents() {
            if (!chart) return;

            // 鼠标悬停事件
            chart.on('mouseover', function (params) {
                if (params.componentType === 'series' && params.seriesType === 'map') {
                    const continent = countryToContinent[params.name];
                    if (continent) {
                        highlightContinent(continent);
                        showCountryInfo(params.name);
                    }
                }
            });

            // 点击事件
            chart.on('click', function (params) {
                if (params.componentType === 'series' && params.seriesType === 'map') {
                    const continent = countryToContinent[params.name];
                    if (continent) {
                        highlightContinent(continent);
                        showCountryInfo(params.name);
                    }
                }
            });

            // 鼠标离开地图
            chart.on('globalout', function () {
                chart.dispatchAction({
                    type: 'unselect',
                    seriesIndex: 0
                });
            });

            // 窗口大小变化
            window.addEventListener('resize', function () {
                chart && chart.resize();
            });
        }

        // 初始化
        function init() {
            document.getElementById('retry-btn').addEventListener('click', loadMapData);
            document.getElementById('reset-btn').addEventListener('click', resetMap);
            loadMapData();
        }

        window.addEventListener('DOMContentLoaded', init);
    </script>
</body>

</html>

到此这篇关于使用Echart.js和world.js实现世界地图的文章就介绍到这了,更多相关Echart.js和world.js世界地图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论