2

How to calculate midpoint of all lines in layers, and add to it layer for midpoint snapping, using OpenLayers 2.13?

I've tried the following code, but does not work:

var features=vectors.features;
var len=vectors.features.length;
for (var i=0 ; i < len ; i++){
    for(var j=0 ; j<features[i].geometry.getVertices().length ; j++){
        points.push(features[i].geometry.getVertices()[j]);
    }
}
i=0;
while(i<points.length){
    xA=points[i].x;
    yA=points[i].y;
    xB=points[i+1].x;
    yB=points[i+1].y;
    xC=(xA+xB)/2;
    yC=(yA+yB)/2;
    midPoints.push(new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(xC,yC)));
    i++;
}
2

I found the solution:

var middlePoints=[];
function createPoint(p1,p2){
    var xC,yC;
    xC=(p1.x+p2.x)/2;
    yC=(p1.y+p2.y)/2;
    var point= new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(xC,yC));
    point.style={strokeColor:"red",strokeOpacity:0.3,fillColor:"red",fillOpacity:0.1,pointRadius:1};
    return point;
}
var state=1;
function getMiddlePoint(){
    if(state==1){
        var points=[];
        var features=vectors.features;
        var len=vectors.features.length;
        var point;
        for (var j=0 ; j < len ; j++){
            for(var i=0 ; i < features[j].geometry.getVertices().length-1; i+=2) {
                var prevVertex =features[j].geometry.getVertices()[i];
                var nextVertex = features[j].geometry.getVertices()[i + 1];
                if(prevVertex.CLASS_NAME == "OpenLayers.Geometry.Point" &&
                    nextVertex.CLASS_NAME == "OpenLayers.Geometry.Point") {
                    point = createPoint( prevVertex, nextVertex);
                    middlePoints.push(point);
            }
            }
        }
        vectors.addFeatures(middlePoints);
        vectors.refresh({force:true});
        vertexSnap.activate();
        state=0;
    }else{
        vectors.removeFeatures(middlePoints);
        middlePoints=[];
        state=1;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.