2016-08-11 33 views
0

我用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); 
}); 
+0

我不知道太多关于这个库,但它看起来像你注册两个'click'处理程序,两者都单独执行。因此,你看到两个弹出窗口。我建议只在一个处理程序中处理click事件,然后根据返回的功能实现一些显示弹出窗口的逻辑。 – forrert

回答

0

你注册的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); 
}); 
+0

谢谢!这工作完美。 – Juiblex