功能图完成后如何触发功能?

时间:2018-02-13 13:44:57

标签: javascript gis openlayers

我在项目中使用openlayers 2.

我在绘图完成后在地图上绘制了3种类型的特征我需要触发名为featureDrawed的函数。

她是我的代码:

drawControl = {
    point: new OpenLayers.Control.DrawFeature(new OpenLayers.Layer.Vector("Point Layer"), OpenLayers.Handler.Point } }),
    line: new OpenLayers.Control.DrawFeature(new OpenLayers.Layer.Vector("Line Layer"), OpenLayers.Handler.Path),
    polygon: new OpenLayers.Control.DrawFeature(new OpenLayers.Layer.Vector("Polygon Layer"), OpenLayers.Handler.Polygon)
}

for (var key in drawControl) {
    control = drawControl[key];
    controls.push(control);
}

以下是用户选择要绘制的要素的html:

    <div data-role="popup" id="popupShapes" data-theme="none" style="z-index:999">
        <div data-role="collapsibleset" data-theme="b" data-content-theme="a" style="margin:0; width:250px;">
            <div data-role="listview" data-inset="false">
                <ul data-role="listview">
                    <li>
                        <input type="radio" name="type" value="point" id="pointToggle" />
                        <label for="pointToggle">draw point</label>
                    </li>
                    <li>
                        <input type="radio" name="type" value="line" id="lineToggle" />
                        <label for="lineToggle">draw line</label>
                    </li>
                    <li>
                        <input type="radio" name="type" value="polygon" id="polygonToggle" />
                        <label for="polygonToggle">draw polygon</label>
                    </li>
                </ul>
            </div>
        </div>
    </div>

这是用户选择要绘制的形状后触发的事件。

$("#popupShapes ul li input").click(function () {
    var val = $(this).val();

    for (key in drawControl) {
        var control = drawControl[key];
        if (val == key) {
            control.activate();
        } else {
            control.deactivate();
        }
    }
});

代码工作正常。但问题是,我无法创建在地图上绘制要素后触发的事件。

2 个答案:

答案 0 :(得分:0)

您可以使用addEventListener和dispatchEvent。 例如:

function DrawSomething(){
/*drawing*/
let event=new Event('featureDrawed');
this.dispatchEvent(event);
}

代码中的某处

DrawSomething.addEventListener('featureDrawed', function(){
/*action you want to do when all you want is drawn*/
})

注意:在绘制图片之前需要addEventListener

答案 1 :(得分:0)

声明要在绘制结束时调用的函数:

var onDrawEnd = function(e) {
    console.log('feature added', e.feature);
    //your logic
};

为每个控件注册一个监听器:

for (var key in drawControl) {
    control = drawControl[key];
    control.events.register('featureadded', null, onDrawEnd);
    controls.push(control);
}