无法在openlayers 3矢量图层中绘制多边形和线条

时间:2015-10-30 17:46:37

标签: openlayers-3

我写了一个代码,该代码应该获得刚刚在矢量图层上创建的特征。

<select id="type">
    <option value="Point">Point</option>
    <option value="LineString">LineString</option>
    <option value="Polygon">Polygon</option>
</select>

//is actually empty    
var sourceVector = new ol.source.Vector({});

layerVector = new ol.layer.Vector({
    id: 'myLayer',
    source: sourceVector,
    style:cStyle // I set a style, I just dont iclude it for brevity
});

var draw;
var typeSelect = document.getElementById('type');

function addInteraction() {
    draw = new ol.interaction.Draw({
        source: sourceVector,
        type: typeSelect.value
    });
    map.addInteraction(draw);
}

 //when something is selected by the dropdown
 //remove the previous interaction and reset it
typeSelect.onchange = function(e) {
    map.removeInteraction(draw);
    addInteraction();
};

addInteraction();

    //when drawing is finished, get coords and print them
    draw.on('drawend',
    function(evt) { 
        var justNowFeature = evt.feature;
        var featureGeom = justNowFeature.getGeometry().getCoordinates();
        console.log("FEATURESGEOJSON  "+featureGeom );
    }
);

这也适用于获取几何类型

var featureGeom = justNowFeature.getGeometry().getType();

实际上我想要保存的只是类型和坐标,所以我很好。

除此之外,这仅适用于积分。如果我选择Polygon或LineString,它不会在控制台中打印任何内容,并且我没有收到任何错误,它只是不起作用。

任何解决方案?

谢谢

1 个答案:

答案 0 :(得分:1)

您需要在addInteraction函数中放置'drawend'事件初始化。在这里查看小提琴。 fiddle here 初始化'drawend'事件时,不存在绘制交互。 Firebug虽然应该通知你"draw" is undefined

这是你的代码。我在CAPITALS做了一些评论来解释。

<select id="type">
    <option value="Point">Point</option>
    <option value="LineString">LineString</option>
    <option value="Polygon">Polygon</option>
</select>

//is actually empty    
var sourceVector = new ol.source.Vector({});

layerVector = new ol.layer.Vector({
    id: 'myLayer',
    source: sourceVector,
    style:cStyle // I set a style, I just dont iclude it for brevity
});

var draw;
var typeSelect = document.getElementById('type');

function addInteraction() {
    draw = new ol.interaction.Draw({
        source: sourceVector,
        type: typeSelect.value
    });
    map.addInteraction(draw);
}

 //when something is selected by the dropdown
 //remove the previous interaction and reset it
typeSelect.onchange = function(e) {
    //HERE YOU REMOVE THE INTERCATION AND THUS ALL LISTENERS 
    //ASIGNED TO IT REMOVED
    // SO YOU NEED TO REASIGN THE LISTENERS AS THIS IS A BRAND NEW INTERACTION
    map.removeInteraction(draw);
    addInteraction();
};

addInteraction();

    //when drawing is finished, get coords and print them
    //HERE YOU JUST ASIGN THE LISTENER AT STARTUP. 
    //THIS HAPPENS ONCE AND NOT EACH TIME YOU 
   // ADD BACK THE INTERACTION
    draw.on('drawend',
    function(evt) { 
        var justNowFeature = evt.feature;
        var featureGeom = justNowFeature.getGeometry().getCoordinates();
        console.log("FEATURESGEOJSON  "+featureGeom );
    }
);