首页 > 解决方案 > 没有悬停事件的 Amcharts4 标记 html-tooltips

问题描述

我正在使用示例将地图标记放在点击上,我的目标是mapMarker.tooltipHTML默认显示元素,而不是将鼠标悬停在它们上。欢迎使用任何替代方法,例如创建 html 标记。

标签: angulartypescriptamchartsamcharts4

解决方案


Tooltip好吧,要让s 以您想要的方式工作,需要几个步骤。首先,工具提示通常是一个单例,而不是每个多边形或每个mapImage,它们实际上在他们的系列中共享一个。所以每个人都必须使用自己的工具提示(大多数情况下,mapImage下面是imageSeries.mapImages.template):

mapImage.tooltip = new am4core.Tooltip();

接下来,启用工具提示的条件(通常在悬停时)是是否存在tooltipTexttooltipHTML设置不是空字符串。

mapImage.tooltipText = "Latitude: {latitude}\nLongitude: {longitude}";

悬停时显示的工具提示是默认行为,防止这种情况的最简单方法是禁用鼠标交互mapImage

mapImage.interactionsEnabled = false;

现在,一旦创建了标记,我们将只显示工具提示:

mapImage.events.once("inited", function(event) {
  event.target.showTooltip();
});

默认情况下,工具提示position已经设置为,"fixed"我们只需要它显示在标记上方,在本例中为 32x32 像素,缩小 30%,因此我们只需通过'将其向上移动 32 * .7属性:pointerOrientation"vertical"mapImagetooltipY

mapImage.nonScaling = true; // this is also necessary so the size/vertical shift is predictably the same
mapImage.tooltipY = -32 * .7;

最后但并非最不重要的一点是,工具提示在缩放时不会保持其位置,因此我们必须自己通过监听缩放变化、将地图图像的纬度/经度坐标转换为图表 x/y 坐标并将其传递给每个工具提示:

chart.events.on("zoomlevelchanged", function() {
  imageSeries.mapImages.each(function(mapImage) {
    var point = chart.geoPointToSVG({ latitude: mapImage.latitude, longitude: mapImage.longitude });
    mapImage.tooltip.moveTo({ x: point.x, y: point.y - (32 * .7)});
  });
});

这是一个演示:

https://codepen.io/team/amcharts/pen/698eb4a11c35733850fbc084631bfc21

附录(2019-04-11):

您还可以将纬度/经度属性绑定到数据并通过该方法创建mapImages该方式addData,例如

var mapImage = imageSeries.mapImages.template;
mapImage.propertyFields.latitude = "latitude";
mapImage.propertyFields.longitude = "longitude";

// You can even start off with some markers at the onset
// From our Animations along lines demo: https://www.amcharts.com/demos/animations-along-lines/
imageSeries.data = [
  { "latitude": 48.8567, "longitude": 2.3510, "name": "Paris"},
  { "latitude": 43.8163, "longitude": -79.4287, "name": "Toronto"},
  { "latitude": 34.3, "longitude": -118.15, "name": "Los Angeles"},
  { "latitude": 23, "longitude": -82, "name": "Havana"},
];

chart.seriesContainer.events.on("hit", function(ev) {
  var coords = chart.svgPointToGeo(ev.svgPoint);
  // var marker = imageSeries.mapImages.create();  
  // marker.latitude = coords.latitude;
  // marker.longitude = coords.longitude;
  imageSeries.addData({
    latitude: coords.latitude,
    longitude: coords.longitude,
  });
});

如果要从data数组的开头删除标记,请使用removeData方法. 如果要使用 修改data数组Array.splice,如果数组之后不为空,则必须运行imageSeries.invalidateData()以更新视图。如果数组为空,最好只设置imageSeries.data = undefined。还要记住,该addData方法有一个第二个参数,它也从数组的开头删除项目。

另请注意,您必须在他们的事件中手动dispose标记工具提示。"beforedisposed"

这是一个更新和改进的演示,其中包括一些错误修复:

https://codepen.io/team/amcharts/pen/fee1cb6db8971ec3eff6541ad52bab6d


推荐阅读