[GIS] Where is the drawn feature when the drawend is triggered in OL3

eventsintersectionjavascriptopenlayers

I have written a piece of code to check if the drawn line is intersecting other lines in the vector layer. If so, then the line should be split and new lines should be added to the layer. here is my code:

The events:

lineStringdraw.on('drawend', function(e2) {
var featureEnd = e2.feature;
var featureGeom = featureEnd.getGeometry();
var endNodeCoordinates = featureGeom.getLastCoordinate();
snapIndex= endNodeCoordinates.length-1;
checkSnapping(nodes, endNodeCoordinates);
if(snap){
    var featureCoordinates = featureGeom.getCoordinates();
    featureCoordinates[featureCoordinates.length-1]= snapToNode;
    featureGeom.setCoordinates(featureCoordinates);
    featureEnd.setGeometry(featureGeom);
    featureEnd.changed();
}
checkIntersection(featureEnd);
if (tempList.length!==0){
    //lineStringdraw.finishDrawing();    //my first solutuion
    //vector2.getSource().getFeatures().removeFeature([vector2.getSource().getFeatures().length-1]);
    //delete e2.feature;   //my second solotion.
    for (i=0;i<tempList.length;i++){vector2.getSource().addFeature(tempList[i]);}   
}

drawing = false;
drawing_feature = null;
});

checkIntersection():

this function checks if the currently drawn line is intersecting other lines. if so then it calls the split function which will produce final lines to be added to the layer.

There is only one problem. The currently drawn line is also added to the vector layer and I cannot stop it as this feature is not yet added to the source so I cannot remove it from source. And also I cannot remove it from the draw interaction (at least I dont know how to remove it). It seems that the line is added after the drawend event is handled but how I can prevent it from happening. Any Idea?

EDIT

I now use the addfeature event for the source. when the feature is added, it will be checked for the intersection. but there rises another problem: when I add the new features from split function they will be checked again and again. I tried .unByKey() to remove the listener so that I can add the new features but then I cannot reactivate it.

var addFeatureEventListener = vector2.getSource().on('addfeature', function(e){
var currentFeture = vector2.getSource().getFeatures()[vector2.getSource().getFeatures().length-1]; 
var newLines =  checkIntersection(currentFeture);
vector2.getSource().unByKey(addFeatureEventListener);
console.info("the listener is deactivated now....");
vector2.getSource().addFeatures(newLines);
vector2.getSource().changed();  
});

I am kinda fed up. I checked this answer but I seem cannot understand it.

Best Answer

Try this:

lineStringdraw.on('drawstart', function(){
    vector2.getSource().once('addfeature', handleAddFeature);
});

function handleAddFeature(evt) {
    var feature = evt.feature;
    // ...
}

Add the listener just when start drawing. OL will remove it for you since you are using once.