2

我目前正在创建一个应用程序原型,其中包含一个 OpenLayers 组件(地图本身)。

我想创建具有附加属性的特殊“功能”。

它们应该从OpenLayers.Feature.Vector继承,也就是说,使用它的构造函数和自定义参数和附加属性。

我一直在寻找,但我找不到任何简单的例子来说明如何做到这一点。

*注意:我的应用程序对象结构不是基于“OpenLayers.Class”类型,因此它们是常见的 javascript 对象。

所以这里是应该从 OpenLayers.Feature.Vector 继承的 Class 并且应该返回它的一个特殊实例,

// Class "SpecialRegion"
function SpecialRegion(bounds, options) {

 /* should return an OpenLayers.Feature.Vector with additional properties (objects) which makes this class different */

}

提前致谢。

4

1 回答 1

2

如果要扩展我强烈推荐的 OpenLayers.Feature.Vector 类,则必须使用 OpenLayers.Class 对象:

SpecialRegion = OpenLayers.Class(OpenLayers.Feature.Vector, {
    customAttribute: 'value',

    /**
     * OpenLayers Constructor
     */
    initialize: function(bounds, options) {
        // Call the super constructor, you will have to define the variables geometry, attributes and style
        OpenLayers.Feature.Vector.prototype.initialize.apply(this, {geometry, attributes, style});
        this.customAttribute = 'new value';
    },

    // Each instance will share this method. It's clean and efficient
    customMethod: function(param) {
        ...
    }
});

实例化

var myVector = new SpecialRegion(bounds, options);
myVector.customMethod(param);
var val = myVector.customAttribute;

如果您只想为单个实例定义特殊方法和/或属性,而不必定义它自己的类:

注意:如果您经常这样做,您的应用程序可能会变得非常混乱,我建议您使用上述解决方案。

function customMethod2 = function(param) {
    ...
};

function SpecialRegion(bounds, options) {
    // Call the constructor, you will have to define the variables geometry, attributes and style
    var vector = new OpenLayers.Feature.Vector(geometry, attributes, style);

    vector.customAttribute = 'new value';

    // Each instance created with SpecialRegion will have their own copy of this method, the code is cleaner but it's memory inefficient
    vector.customMethod = function(param) {
        ...
    };

    // Each instance share the same copy of this method (defined on top), the code is harder to read/maintain but it's more memory efficient
    vector.customMethod2 = customMethod2;

    return vector;
};

实例化

var myVector = SpecialRegion(bounds, options);
// Don't use the keyword 'new' here, SpecialRegion is a function, not a proper class.
myVector.customMethod(param);
myVector.customMethod2(param);
var val = myVector.customAttribute;
于 2012-07-03T03:39:54.153 回答