OpenLayers.Control.Button的触发器参数不会被调用

时间:2011-05-11 14:06:41

标签: button triggers click openlayers

我正在尝试向OpenLayers地图添加一个按钮,该按钮应该在单击时调用JS函数。我设法让它看起来像我想要的,但触发功能不起作用。

如果我有Control.Navigation存在,单击按钮似乎开始拖动事件,我可以通过单击该按钮来拖动地图。但即使我删除了所有其他控件,按钮的触发器处理程序也不会被调用。

我也尝试添加“autoActivate”参数(由于某些原因,它不会让控件自动激活),我已经尝试在添加它之后为按钮调用activate()函数,这似乎切换控件的“活动”属性,但它仍然不响应点击。

有人能指出我正确的方向吗,或发布一个有效的例子?我的非工作示例如下。

谢谢, 贾尼斯

<html>
<head>
<title>OpenLayers.Control.Button</title>
<style text="text/css">
.olControlButton {
    position: absolute;
    top: 0;
    right: 0;
    background: red;
    width: 22px;
    height: 22px;
}
</style>
<script type="text/javascript" src="http://openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
var map;
var panel;

function buttonClicked()
{
    alert ('Button clicked.');
}

function init()
{
    map = new OpenLayers.Map ('map', {controls: [/*new OpenLayers.Control.Navigation()*/]});
    map.addLayer (new OpenLayers.Layer.WMS ("OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: 'basic'}));
    map.zoomToMaxExtent();

    panel = new OpenLayers.Control.Panel();
    map.addControl (panel);

    panel.addControls ([new OpenLayers.Control.Button ({autoActivate: true, displayClass: 'olControlButton', trigger: buttonClicked, title: 'Button is to be clicked'})]);
    //panel.controls[0].activate(); <-- this does not help.
}
</script>
</head>
<body onload="init()">
    <div id="map" style="border: 2px solid black; height: 500px"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:8)

按钮DIV无法接收点击事件,因为面板DIV(包含按钮)没有尺寸。您也应该为面板DIV设置样式。此外,面板下按钮的类别为olControlButtonItemActive,因此您需要为其设置样式而不是olControlButton

OpenLayers.Control.Panel处理子控件的激活,让它自动激活按钮,在实例化新的Panel实例时,应将defaultControl选项设置为button。否则,您必须先单击按钮一次才能实际触发它。

<html>
<head>
<title>OpenLayers.Control.Button</title>
<style text="text/css">
.olControlButtonItemActive {
    position: absolute;
    top: 0;
    right: 0;
    background: red;
    width: 22px;
    height: 22px;
}

.olControlPanel {
    width: 50px;
    height: 50px;
    border: 1px solid black;
}

</style>
<script type="text/javascript" src="http://openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
var map;
var panel;

function buttonClicked()
{
    alert ('Button clicked.');
}

function init()
{
    map = new OpenLayers.Map ('map', {controls: [/*new OpenLayers.Control.Navigation()*/]});
    map.addLayer (new OpenLayers.Layer.WMS ("OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: 'basic'}));
    map.zoomToMaxExtent();

    button = new OpenLayers.Control.Button ({displayClass: 'olControlButton', trigger: buttonClicked, title: 'Button is to be clicked'});

    panel = new OpenLayers.Control.Panel({defaultControl: button});
    panel.addControls([button]);
    map.addControl (panel);

}
</script>
</head>
<body onload="init()">
    <div id="map" style="border: 2px solid black; height: 500px"></div>
</body>
</html>