【问题标题】:How to add "click" listener on marker in mapbox-gl-js如何在 mapbox-gl-js 的标记上添加“点击”侦听器
【发布时间】:2015-10-05 13:20:33
【问题描述】:

我使用以下示例在地图上添加了一些标记:

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

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

【问题讨论】:

    标签: mapbox-gl-js


    【解决方案1】:

    对于初学者,在 map.addLayer() 函数中,您可能用于将标记添加到地图,您需要在配置对象中设置 "interactive": true。

    map.addLayer({
                    "id": "YOUR LAYER ID",
                    "interactive": true,
                    "type": "symbol",
                    "source": "YOUR LAYER SOURCE",
                    "layout": {
                      "icon-image": "YOUR LAYER ICON IMAGE",
                      "text-font": "Open Sans Semibold, Arial Unicode MS Bold",
                      "text-offset": [0, 0.6],
                      "text-anchor": "top"
                    },
                    "paint": {
                      "text-size": 12,
                      "icon-size": 1,
                      "icon-opacity": 0
                    }
                });
    

    之后,您需要在地图上设置一个点击处理程序,并检查该点是否位于您的某个要素(标记)上方。

    map.on('click', function(e) {
    
        console.log(e);
    
          map.featuresAt(e.point, {radius: 100, layer: 'YOUR MARKER LAYER ID'}, function(err, features) {
                console.log(features[0]);
    
          });
    
        });
    

    您可以查看their website 的文档以获取更多信息。如果您有任何问题,请告诉我。

    【讨论】:

    • 这是否仅适用于在 Mapbox Studio 中添加的图层,或者也适用于使用map.addLayer() 添加的图层?
    • 它应该适用于两者。在您遇到其中一种方法的问题后?
    【解决方案2】:

    以下 sn-p 来自 Mapbox-gl-js 示例:Display a popup on click

     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' : '';
    });
    

    【讨论】:

      【解决方案3】:

      考虑到最近发布的 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.");
         }
      ); 
      

      【讨论】:

        【解决方案4】:

        我也遇到了同样的问题,但我找到了一种解决方法,而无需创建 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");
                });
              });
        

        【讨论】:

        • 这似乎是在标记上设置点击监听器的最全面的方法
        • 这种方式占用的代码最少。如果有人需要快速复制和粘贴,这是一个展示示例的代码笔 -> codepen.io/darrow8/pen/gOPWzjP?editors=1010
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-25
        • 1970-01-01
        • 2016-01-01
        • 2021-10-21
        • 2021-10-15
        • 2016-12-10
        • 1970-01-01
        相关资源
        最近更新 更多