OpenLayers矢量图层特征处理程序

时间:2011-12-21 20:57:54

标签: vector listener handler openlayers

我会有一个openlayers矢量图层,其中的功能散布在整个地图上。我希望能够点击某个功能并显示一条消息。

我不确定是否有办法为每个功能添加一个监听器/处理程序。

有什么想法吗?

3 个答案:

答案 0 :(得分:8)

添加SelectFeture控件:

var selectFeature = new OpenLayers.Control.SelectFeature(vector_layer);
map.addControl(selectFeature);
selectFeature.activate();

之后,您可以在矢量图层上收听选择/取消选择事件:

vector_layer.events.on({
  'featureselected': function(feature) {
       //display your message here
  },
  'featureunselected': function(feature) {
       //hide message
  }
});

答案 1 :(得分:5)

您需要结合使用SelectFeature控件和OpenLayers.Popup类之一,例如OpenLayers.Popup.FramedCloud。这是一个例子:

http://openlayers.org/dev/examples/select-feature-openpopup.html

在该示例中,尝试使用“绘制多边形”选项绘制多边形(双击地图以完成多边形)。然后使用“单击时选择多边形”并单击多边形,您将获得一个框架云弹出窗口。

您可以查看该页面的来源,了解它是如何完成的。以下是代码的相关部分。当然,您可以将message更改为您想要在框架云中显示的内容:

    var map = <your OpenLayers.Map object>;
    var polygonLayer = <your vector layer>;

    selectControl = new OpenLayers.Control.SelectFeature(polygonLayer,
            {onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
    map.addControl(selectControl); // not in the example, but do this

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

    function onFeatureSelect(feature) {
        var message = "<div style='font-size:.8em'>Feature: " + feature.id +"<br>Area: " + feature.geometry.getArea()+"</div>";

        selectedFeature = feature;
        popup = new OpenLayers.Popup.FramedCloud("chicken", 
            feature.geometry.getBounds().getCenterLonLat(),
            null,
            message,
            null, true, onPopupClose);
        feature.popup = popup;
        map.addPopup(popup);
    }

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

以下是您将使用的控件的参考:

答案 2 :(得分:0)

如果有很多矢量图层,是否需要为每一层写“layer_name.events.on ...”?是否可以制作图层列表并为所有图层分配“.events.on”?

相关问题