Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

javascript - 使用Mapbox gl js在悬停到自定义标记上添加弹出窗口(Adding popups on hovering to custom markers using Mapbox gl js)

I'm adopting this example but I need popups to appear on hover not on click.

(我采用此示例,但是我需要弹出窗口显示在悬停而不是单击的位置。)

Here is how popups are added now:

(现在是如何添加弹出窗口:)

new mapboxgl.Marker(el, {
  offset: [0, -25]
})
.setLngLat(marker.geometry.coordinates)
.setPopup(new mapboxgl.Popup()//add popups
    .setHTML('<h3>' + marker.properties.title + '</h3><p><a href="' + marker.properties.link + '" target="_blank">' + marker.properties.description + '</a></p><p><a href="' + marker.properties.link + '" target="_blank"><img src="' + marker.properties.picture + '" title="" /></a></p>'))
.addTo(map);

It is my jsFiddle , could anyone help me to fix that problem?

(这是我的jsFiddle ,有人可以帮助我解决该问题吗?)

  ask by Anton translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

mapboxgl.Marker are implemented as simple HTML <div> elements.

(mapboxgl.Marker被实现为简单的HTML <div>元素。)

You can attach standard event listener to them and toggle the popup manually:

(您可以将标准事件侦听器附加到它们,并手动切换弹出窗口:)

const marker = new mapboxgl.Marker({/* options */});
const markerDiv = marker.getElement();

markerDiv.addEventListener('mouseenter', () => marker.togglePopup());
markerDiv.addEventListener('mouseleave', () => marker.togglePopup());

See docs: https://docs.mapbox.com/mapbox-gl-js/api/#marker#getelement

(参见文档: https : //docs.mapbox.com/mapbox-gl-js/api/#marker#getelement)

EDIT: Preventing the popup from opening on click

(编辑:防止单击打开弹出窗口)

I tried did some testing, and the only thing reliably working is to call marker.togglePopup() in your own click handler

(我尝试进行了一些测试,唯一可靠的工作是在您自己的点击处理程序中调用marker.togglePopup())

map.on('click', event => {
  const target = event.originalEvent.target;
  const markerWasClicked = markerDiv.contains(target);

  marker.togglePopup();
});

Full example: https://jsfiddle.net/am2jwtzg/

(完整示例: https//jsfiddle.net/am2jwtzg/)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...