openlayer通过策略更改功能属性

时间:2014-06-15 18:47:40

标签: openlayers

我将要素的属性值更改为自定义策略,但在绘制要素时,要素不会采用新的属性值。

这是我正在做的测试:

OpenLayers.Strategy.LabelChange =  OpenLayers.Class(OpenLayers.Strategy, {

    activate: function() {
        var activated = OpenLayers.Strategy.prototype.activate.call(this);
        if(activated) {
            this.layer.events.on({
                "moveend": this.filter,
                scope: this
            });
        }
        return activated;
    },

    deactivate: function() {
        var deactivated = OpenLayers.Strategy.prototype.deactivate.call(this);
        if(deactivated) {
            this.layer.events.un({
                "moveend": this.filter,
                scope: this
            });
        }
        return deactivated;
    },

    filter: function()  {
        console.log('labels updated');
        for (var i = 0; i < this.layer.features.length; i++) {
            var f = this.layer.features[i];
            f.attributes.labelName = 'label updated';
        }
    }
});

var features = new Array(15);

// create random reatures
for (var i=0; i<features.length; i++) {
    var x = (360 * Math.random()) - 180;
    var y = (180 * Math.random()) - 90;

    features[i] = new OpenLayers.Feature.Vector(
        new OpenLayers.Geometry.Point(x ,  y), 
        {
            labelName: 'label '+ i
        }
    );
}

var style = new OpenLayers.Style({
    strokeWidth:0,
    pointRadius: 2,
    fillOpacity:0,
    label: "${labelName}",
    fontColor: "#333333",
    fontFamily: "sans-serif",
    fontWeight: "bold",
});

// Create a vector layer and give it your style map.
var labels = new OpenLayers.Layer.Vector("labels", {
    styleMap: new OpenLayers.StyleMap(style),
    strategies:[new OpenLayers.Strategy.LabelChange ()]

});

labels.addFeatures(features);

var map = new OpenLayers.Map({
    div: "map",
    layers: [
        new OpenLayers.Layer.WMS(
            "OpenLayers WMS",
            "http://vmap0.tiles.osgeo.org/wms/vmap0",
            {layers: "basic"}
        ),
        labels
    ],
    center: new OpenLayers.LonLat(0, 0),
    zoom: 1
});

听到jsfiddle: http://jsfiddle.net/ccrafael/aXyqW/1/

谢谢&amp;问候,拉斐尔。

2 个答案:

答案 0 :(得分:0)

我观察到默认标签不会更新,但是当您执行任何操作时,重绘图层(如放大/缩小)标签会更新为新值。 所以我在末尾添加了以下一行到重绘图层,以便重新绘制图层以获取最新的属性值。

// Added this line so features updates labelName with newly set attribute value.
labels.redraw();

更新了JSFiddle: http://jsfiddle.net/dWZw6/1/

希望这会对你有所帮助。

答案 1 :(得分:0)

最后,找到的方法是从图层中删除要素,修改要素并再次将要素添加到图层。

filter: function()  {
    console.log('labels updated');
    var features = this.layer.features;
    this.layer.removeAllFeatures();
    for (var i = 0; i < features.length; i++) {
        var f = features[i];
        f.attributes.labelName = 'label updated';
    }
    this.layer.addFeatures(features);
}

这里的小提琴: http://jsfiddle.net/ccrafael/aXyqW/2/