计算捕捉的中点

时间:2015-09-06 06:46:13

标签: openlayers

如何计算图层中所有线条的中点,并使用 OpenLayers 2.13 添加到中间点捕捉的图层?

我已尝试过以下代码,但无效:

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++;
}

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

我找到了解决方案:

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;
    }
}