开发者问题收集

如何在 mapbox-gl-js 中的标记上添加“点击”监听器

2015-07-16
56576

我按照以下示例在地图上添加了几个标记:

https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/

现在我想在用户点击标记图像时显示弹出窗口,但我找不到优雅的解决方案。有什么帮助吗?

3个回答

我也遇到了同样的问题,但我找到了一种无需创建 html 元素的解决方法。

我使用了 getElement() 函数,该函数返回类似 HTML 元素的标记,然后附加了点击事件。

this.service.getAllData().forEach(e => {
  // create MapBox Marker
  const marker = new mapboxgl.Marker().setLngLat([e.lon, e.lat]).addTo(this.map);
  // use GetElement to get HTML Element from marker and add event
  marker.getElement().addEventListener('click', () => {
    alert("Clicked");
  });
});
beginner's_luck
2019-11-23

考虑到 MapBox-Gl-js 的最新版本。只需添加带有标记的弹出窗口,即可直接完成。

// create a simple popup.
var popup = new mapboxgl.Popup({offset: 25})
    .setText('Construction on the Washington Monument began in 1848.');

// create DOM element for the marker
var el = document.createElement('div');
el.innerHTML = "Marker1";
el.id = 'marker';

// create the marker
new mapboxgl.Marker(el, {offset:[-25, -25]})
    .setLngLat(monument)
    .setPopup(popup) // sets a popup on this marker
    .addTo(map);

其余的,您可以拥有自己设计的弹出窗口

var html = '<div class="marker-popup">I am a custom pop-up</div>';

var customPopUp = new mapboxgl.Popup(
    {
       anchor: 'bottom',   // To show popup on top
       offset: { 'bottom': [0, -10] },  // To prevent popup from over shadowing the marker.
       closeOnClick: false   // To prevent close on mapClick.
    }
).setHTML(html); // You can set any valid HTML.

供参考 https://www.mapbox.com/mapbox-gl-js/example/set-popup/

还有一个有用的东西,要在标记上附加点击事件,您可以通过在标记元素上附加点击事件监听器来实现,例如

el.addEventListener('click', () => 
   { 
      alert("Marker Clicked.");
   }
); 
Rahul
2017-08-25

以下代码片段来自 Mapbox-gl-js 示例: 点击时显示弹出窗口

map.on('click', function (e) {
    var features = map.queryRenderedFeatures(e.point, { layers: ['places'] });

    if (!features.length) {
        return;
    }

    var feature = features[0];
    // Use Feature and put your code
    // Populate the popup and set its coordinates
    // based on the feature found.
    var popup = new mapboxgl.Popup()
        .setLngLat(feature.geometry.coordinates)
        .setHTML(feature.properties.description)
        .addTo(map);
});

// Use the same approach as above to indicate that the symbols are clickable
// by changing the cursor style to 'pointer'.

map.on('mousemove', function (e) {
    var features = map.queryRenderedFeatures(e.point, { layers: ['places'] });
    map.getCanvas().style.cursor = (features.length) ? 'pointer' : '';
});
skarfa
2017-01-20