如何在 Mapbox GL JS 中的可点击多边形顶部放置可点击标记

How to place a clickable marker on top of a clickable polygon in Mapbox GL JS

我用 mapbox-gl-js 制作了一张地图并添加了停车场图层,点击后会打开一个带有方向的弹出窗口。然后我在停车场层的顶部放置了一些可点击的标记(用于公交车站、无障碍停车场等)。当我单击停车场上的标记时,停车场弹出窗口和标记弹出窗口都会弹出。如果有标记弹出窗口,如何防止多边形图层触发弹出窗口?我不想同时显示两个弹出窗口。

相关代码如下:

// Add a layer showing the parking lots
map.addLayer({
    "id": "parking-layer",
    "type": "fill",
    "source": "parking-buttons",
    "layout": {},
    "paint": {
        "fill-color": "hsla(0, 0%, 0%, 0)",
        "fill-outline-color": "hsla(0, 0%, 0%, 0)"
    }
});

// Add a layer showing the bus stop
map.addLayer({
    "id": "bus",
    "type": "symbol",
    "source": "bus",
    "layout": {
        "icon-image": "{icon}-11",
        "icon-allow-overlap": true
    },
    "paint": {
        "icon-opacity": {"stops": [[15.49, 0], [15.5, 1]]}
    }
});

// When a click event occurs for a polygon, open a popup with details
map.on('click', function (e) {
    var features = map.queryRenderedFeatures(e.point, { layers: ['parking-layer', 'buildings-layer'] });

    if (!features.length) {
        return;
    }

    var feature = features[0];

    // Populate the popup and set its coordinates
    var popup = new mapboxgl.Popup()
        .setLngLat(map.unproject(e.point))
        .setHTML(feature.properties.description)
        .addTo(map);
});

// When a click event occurs for a node, open a popup with details
map.on('click', function (e) {
    var features = map.queryRenderedFeatures(e.point, { layers: ['bus', 'ephone'] });

    if (!features.length) {
        return;
    }

    var feature = features[0];

    // Populate the popup and set its coordinates
    var popup = new mapboxgl.Popup()
        .setLngLat(feature.geometry.coordinates)
        .setHTML(feature.properties.description)
        .addTo(map);
});

您在 click 事件上注册了两个单独的处理程序,如果有重叠的功能,这两个处理程序最终都会显示一个弹出窗口。

我会尝试在一个 click 处理程序中处理不同的结果,而不是 2:

// When a click event occurs for a polygon, open a popup with details
map.on('click', function (e) {
    var pointFeatures = map.queryRenderedFeatures(e.point, { layers: ['bus', 'ephone'] });

    if (pointFeatures.length > 0) {
        var feature = pointFeatures[0];
        // Populate the popup and set its coordinates
        var popup = new mapboxgl.Popup()
            .setLngLat(feature.geometry.coordinates)
            .setHTML(feature.properties.description)
            .addTo(map);
        return; // don't display any more pop ups
    }

    var polygonFeatures = map.queryRenderedFeatures(e.point, { layers: ['parking-layer', 'buildings-layer'] });

    if (!polygonFeatures.length) {
        return;
    }

    var feature = polygonFeatures [0];

    // Populate the popup and set its coordinates
    var popup = new mapboxgl.Popup()
        .setLngLat(map.unproject(e.point))
        .setHTML(feature.properties.description)
        .addTo(map);
});