0

I use OpenLayers with vector layer to display differents item on the map.

On top of that I want to add for each item (a feature) a pop-up (when click on item display the popup). To do that I have :

function initMap()
    {
     // In this function I add with success the different items to the vectorLayer.
    }

    function finishMap()
    {

        map.addLayer(vectorLayer);

        selectControl = new OpenLayers.Control.SelectFeature(vectorLayer,
            {
                onSelect: onFeatureSelect,
                onUnselect: onFeatureUnselect
            });
        map.addControl(selectControl);
        selectControl.activate();
    }

    function onFeatureClose(evt) {
        selectControl.unselect(selectedFeature);
    }

    function onFeatureSelect(feature) {
        var popup = new OpenLayers.Popup.FramedCloud("popup",
            feature.geometry.getBounds().getCenterLonLat(),
            null,
            feature.description,
            true,
            onFeatureClose);
        popup.panMapIfOutOfView = true;
        popup.autoSize = true;
        feature.popup = popup;

        map.addPopup(popup);
    }

    function onFeatureUnselect(feature) {
        map.removePopup(feature.popup);
        feature.popup.destroy();
        feature.popup = null;
    }

The call for different function is :

  1. initMap();
  2. finishMap();

The problem is : I have only one item (of more than 10) which have a pop-up by clicking on it...

4

1 回答 1

1

通常,将选择处理程序直接实现到层对象(我猜)在 initMap 方法中更容易。使用 eventListeners 属性,如下所示:

    var layer = new OpenLayers.Layer.Vector("Vector layer", { 
        eventListeners: {
            'featureselected':function(evt){
                var feature = evt.feature;
                var popup = new OpenLayers.Popup.FramedCloud("popup",
                    OpenLayers.LonLat.fromString(feature.geometry.toShortString()),
                    null,
                    "<div style='font-size:.8em'>Feature: " + feature.id +"<br>Foo: " + feature.attributes.foo+"</div>",
                    null,
                    true
                );
                feature.popup = popup;
                map.addPopup(popup);
            },
            'featureunselected':function(evt){
                var feature = evt.feature;
                map.removePopup(feature.popup);
                feature.popup.destroy();
                feature.popup = null;
            }
        }
    });

//create selector control
var selector = new OpenLayers.Control.SelectFeature(layer,{
        autoActivate:true
    });

示例实现:http : //openlayers.org/dev/examples/light-basic.html 唯一的区别是 selecotr 对 mouseover 和 mouseout 做出反应,而不是 click(这是通过将选择器的 hover 属性设置为 true 来完成的)。

另外,关于 SO 的一个非常相似的问题:How to add a popup box to a vector in OpenLayers? .

有关课程的更多详细信息,请参阅 OL 文档:http ://dev.openlayers.org/docs/files/OpenLayers-js.html 或询问。

希望至少有一些帮助。

于 2013-09-02T15:46:37.600 回答