
本教程详细介绍了如何使用 am5charts 库创建交互式世界地图,并为地图上的每个国家配置点击事件。核心内容包括设置地图、加载地理数据、为国家数据添加自定义属性(如链接),以及如何正确地在点击事件中获取这些动态数据并实现链接跳转,解决了在 `setall` 后数据检索不准确的问题。
在使用 am5charts 构建交互式地图时,常见的需求是让用户点击地图上的特定区域(如国家)时触发某个动作,例如打开一个外部链接。本教程将指导您如何为 am5charts 地图中的国家添加点击事件监听器,并准确地获取与该国家关联的自定义数据(如 URL),最终实现点击跳转功能。
首先,我们需要一个基本的 HTML 结构和 am5charts 的初始化代码。
HTML 结构 (index.html)
<!DOCTYPE html>
<html>
<head>
<title>am5charts 交互式地图</title>
<link rel="stylesheet" href="css/style.css" media="screen">
</head>
<body>
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/map.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<script src="https://cdn.amcharts.com/lib/5/geodata/worldLow.js"></script>
<script src="https://cdn.amcharts.com/lib/5/geodata/worldHigh.js"></script>
<div id="chartdiv"></div>
<script src="js/script.js"></script>
</body>
</html>CSS 样式 (css/style.css)
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
margin: 0;
padding: 0;
}
#chartdiv {
width: 100%;
height: 95vh; /* 占据视口高度的95% */
}JavaScript 初始化 (js/script.js)
// 创建 Root 实例
var root = am5.Root.new("chartdiv");
// 设置主题
root.setThemes([
am5themes_Animated.new(root)
]);
// 创建 MapChart 实例
var chart = root.container.children.push(
am5map.MapChart.new(root, {
panX: "rotateX",
projection: am5map.geoNaturalEarth1(), // 使用自然地球投影
wheelY: "none", // 禁用滚轮缩放,除非按住Ctrl键
maxPanOut: 0.0
})
);
// 添加背景系列(海洋)
var backgroundSeries = chart.series.unshift(
am5map.MapPolygonSeries.new(root, {})
);
backgroundSeries.mapPolygons.template.setAll({
fill: am5.color(0xd4f1f9), // 海洋颜色
stroke: am5.color(0xd4f1f9),
});
backgroundSeries.data.push({
geometry: am5map.getGeoRectangle(90, 180, -90, -180) // 覆盖全球的矩形
});
// 创建多边形系列(国家)
var polygonSeries = chart.series.push(
am5map.MapPolygonSeries.new(root, {
geoJSON: am5geodata_worldHigh, // 使用高精度世界地理数据
exclude: ["AQ", "FK", "GS", "TF", "HM"], // 排除南极洲等区域
fill: am5.color(0x095256) // 国家默认填充色
})
);
// 设置国家悬停时的样式
polygonSeries.mapPolygons.template.states.create("hover", {
fill: am5.color(0x677935), // 悬停颜色
});
// 禁用Ctrl+滚轮缩放
chart.events.on("wheel", function (ev) {
if (ev.originalEvent.ctrlKey) {
ev.originalEvent.preventDefault();
chart.set("wheelY", "zoom");
} else {
chart.set("wheelY", "none");
}
});为了在点击国家时打开特定链接,我们需要将链接信息与每个国家关联起来。这可以通过 polygonSeries.data.setAll() 方法实现,为每个国家 id 对应的 DataItem 添加一个 description 属性来存储 URL。
// 为特定国家添加自定义数据,包括一个 'description' 属性用于存储链接
polygonSeries.data.setAll([
{
id: "FR", // 法国
name: "France",
description: "https://www.google.com" // 法国的链接
},
{
id: "ES", // 西班牙
name: "Spain",
description: "https://www.amcharts.com" // 西班牙的链接
},
// 可以继续添加更多国家及其链接
]);在 am5charts 中,可以通过 mapPolygons.template.events.on("click", ...) 来监听国家多边形的点击事件。关键在于如何在点击事件发生时,准确地获取到与被点击国家关联的 description(链接)。
直接使用 ev.target.dataItem.get("description") 在某些情况下可能无法如预期工作,尤其是在数据动态更新后。更稳健的方法是利用 polygonSeries.getDataItemById() 获取完整的 DataItem,然后通过其 dataContext 属性访问原始数据对象。
// 添加点击事件监听器
polygonSeries.mapPolygons.template.events.on("click", function (ev) {
// 获取被点击国家的ID
var clickedCountryId = ev.target.dataItem.get("id");
// 根据ID从polygonSeries中获取对应的DataItem
var clickedDataItem = polygonSeries.getDataItemById(clickedCountryId);
// 从DataItem的dataContext中获取'description'属性,即国家链接
var pageToOpen = clickedDataItem ? clickedDataItem.dataContext.description : null;
// 检查链接是否存在且不为空
if (pageToOpen && typeof pageToOpen === 'string' && pageToOpen.trim() !== "") {
console.log("Opening link for " + clickedCountryId + ": " + pageToOpen);
// 使用 window.open() 打开链接
// 这里的 Promise.all 包装在简单打开链接时并非严格必要,
// 但如果需要处理多个异步操作或确保链接打开的顺序,可以保留。
Promise.all([
window.open(pageToOpen, '_blank') // '_blank' 在新标签页打开
]);
} else {
console.log("No valid link found for " + clickedCountryId);
}
});// 创建 Root 实例
var root = am5.Root.new("chartdiv");
// 设置主题
root.setThemes([
am5themes_Animated.new(root)
]);
// 创建 MapChart 实例
var chart = root.container.children.push(
am5map.MapChart.new(root, {
panX: "rotateX",
projection: am5map.geoNaturalEarth1(),
wheelY: "none",
maxPanOut: 0.0
})
);
// 添加背景系列(海洋)
var backgroundSeries = chart.series.unshift(
am5map.MapPolygonSeries.new(root, {})
);
backgroundSeries.mapPolygons.template.setAll({
fill: am5.color(0xd4f1f9),
stroke: am5.color(0xd4f1f9),
});
backgroundSeries.data.push({
geometry: am5map.getGeoRectangle(90, 180, -90, -180)
});
// 禁用Ctrl+滚轮缩放
chart.events.on("wheel", function (ev) {
if (ev.originalEvent.ctrlKey) {
ev.originalEvent.preventDefault();
chart.set("wheelY", "zoom");
} else {
chart.set("wheelY", "none");
}
});
// 创建多边形系列(国家)
var polygonSeries = chart.series.push(
am5map.MapPolygonSeries.new(root, {
geoJSON: am5geodata_worldHigh,
exclude: ["AQ", "FK", "GS", "TF", "HM"],
fill: am5.color(0x095256)
})
);
// 设置国家悬停时的样式
polygonSeries.mapPolygons.template.states.create("hover", {
fill: am5.color(0x677935),
});
// 为特定国家添加自定义数据,包括一个 'description' 属性用于存储链接
polygonSeries.data.setAll([
{
id: "FR", // 法国
name: "France",
description: "https://www.google.com" // 法国的链接
},
{
id: "ES", // 西班牙
name: "Spain",
description: "https://www.amcharts.com" // 西班牙的链接
},
{
id: "DE", // 德国
name: "Germany",
description: "https://www.bing.com" // 德国的链接
},
{
id: "US", // 美国
name: "United States",
description: "" // 没有链接的示例
}
]);
// 添加点击事件监听器
polygonSeries.mapPolygons.template.events.on("click", function (ev) {
var clickedCountryId = ev.target.dataItem.get("id");
var clickedDataItem = polygonSeries.getDataItemById(clickedCountryId);
var pageToOpen = clickedDataItem ? clickedDataItem.dataContext.description : null;
if (pageToOpen && typeof pageToOpen === 'string' && pageToOpen.trim() !== "") {
console.log("Opening link for " + clickedCountryId + ": " + pageToOpen);
Promise.all([
window.open(pageToOpen, '_blank')
]);
} else {
console.log("No valid link found for " + clickedCountryId);
}
});通过本教程,您应该已经掌握了如何在 am5charts 地图中为国家添加点击事件,并正确地获取与被点击国家关联的自定义数据(如外部链接)。关键在于利用 polygonSeries.getDataItemById() 结合 dataContext 来准确检索数据,从而实现灵活的交互功能。这种方法不仅适用于打开链接,也可以扩展到触发其他基于国家数据的自定义行为。
以上就是am5charts 世界地图交互:实现国家点击链接跳转功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号