【问题标题】:OpenLayers Vector Layer Feature HandlerOpenLayers 矢量图层特征处理程序
【发布时间】:2011-12-28 08:56:18
【问题描述】:

我会有一个 openlayers 矢量图层,其特征分散在地图上。我希望能够单击某个功能并显示消息。

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

有什么想法吗?

【问题讨论】:

    标签: vector listener handler openlayers


    【解决方案1】:

    添加 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
      }
    });
    

    【讨论】:

      【解决方案2】:

      您需要结合使用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;
          }
      

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

      【讨论】:

      • 这个例子只有 1 层,但我注意到一旦你开始使用 2 个矢量图层并且需要添加/激活第二个控件以在悬停时执行操作,一个将无法工作。 (并且您需要停用可以使另一个工作的那个)。很奇怪。
      【解决方案3】:

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

      【讨论】:

      • 我自己没有尝试过,但是当您创建 SelectControl 时,您可以发送一个矢量图层数组,而不是像上面的示例那样只发送一个。然后你应该能够在 selectControl.onSelect(){}; 中捕获选择事件;功能。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多