Mapbox GL Popup .setDOMContent示例

时间:2017-02-07 23:25:14

标签: dom mapbox-gl mapbox-gl-js

我正在尝试创建一个自定义按钮,以显示在弹出窗口上,该按钮会生成动态链接(URL)。由于时间原因,我似乎无法通过.setHTML执行此操作,无法在运行时将按钮绑定到函数。所以我想我会尝试新的.setDOMContent 关于此功能如何工作,在线信息为零。我想知道是否有人有一个例子,其中一个按钮被添加到弹出窗口,可以运行一个函数并发送数据。

这是我非常糟糕的尝试。

此功能可创建弹出窗口

function GameObjectPopup(myObject) {
    var features = map.queryRenderedFeatures(myObject.point, {
        layers: ['seed']
    });

    if (!features.length) {
        return;
    }

    var feature = features[0];
    // Populate the popup and set its coordinates
    // based on the feature found.
    var popup = new mapboxgl.Popup()
        .setLngLat(feature.geometry.coordinates)
        .setHTML(ClickedGameObject(feature))
        .setDOMContent(ClickedGameObject2(feature))
        .addTo(map);
};

此函数通过.setHTML

添加html
function ClickedGameObject(feature){
    console.log("clicked on button");
    var html = '';

    html += "<div id='mapboxgl-popup'>";
    html += "<h2>" + feature.properties.title + "</h2>";
    html += "<p>" + feature.properties.description + "</p>";
    html += "<button class='content' id='btn-collectobj' value='Collect'>";
    html += "</div>";
    return html;
}

此函数想要通过.setDOMContent

添加DOM内容
function ClickedGameObject2(feature){
    document.getElementById('btn-collectobj').addEventListener('click', function()
    {
        console.log("clicked a button");
        AddGameObjectToInventory(feature.geometry.coordinates);
    });
}

我正在尝试将来自features.geometry.coordinates的变量传递给函数AddGameObjectToInventory()

单击对象时出现的错误(以便生成弹出窗口)

Uncaught TypeError: Cannot read property 'addEventListener' of null

1 个答案:

答案 0 :(得分:5)

Popup#setHTML采用代表某些HTML内容的字符串:

var str = "<h1>Hello, World!</h1>"
popup.setHTML(str);

Popup#setDOMContent采用实际的HTML节点。即:

var h1 = document.createElement('h1');
h1.innerHTML="Hello, World";
popup.setDOMContent(h1);

这两个代码段都会产生相同的Popup HTML内容。您不希望在单个弹出窗口中使用这两种方法,因为它们是两种不同的方法来执行相同的操作。

您分享的代码中的问题是您尝试使用setDOMContent向您的按钮添加事件侦听器,但您无需访问要添加的Popup对象弹出DOM内容添加到地图后的事件侦听器。以下是我认为你要做的工作版本:https://jsfiddle.net/h4j554sk/