我有一个OpenLayers.Feature.Vector,如下所示:
var multiPol = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiPolygon([polygonGeometry1,polygonGeometry2]));
两个多边形在地图上表示相同的逻辑对象(“实体”),比如云。这就是我将它们保留在一个功能中的原因。 我想绘制它,以便在将多边形(polygonGeometry1,polygonGeometry2)的每个组件添加到图层时以不同的颜色绘制:
var layer = new OpenLayers.Layer.Vector("polygonLayer");
layer.addFeatures([multiPol]);
我已经看过OpenLayers中的样式,样式图和规则,但它们似乎不够用。它们使我能够绘制具有不同颜色的每种几何类型,但前提是它们属于不同的特征(向量)。有没有办法解决这个问题?我真的必须为每个多边形使用单独的Vector吗?
答案 0 :(得分:2)
Jon Snyder提出的解决方案为我们提供了一个总体思路,但最终没有完全发挥作用(特别是基于OpenLayers 2.1x,此任务不需要扩展OpenLayers.Layer.Vector
)。
我们创建了一个类YourApp.Handler.EndPointsPath
(扩展OpenLayers.Handler.Path
),其中函数geometryClone()
返回类型YourApp.Geometry.EndPointsPath
的新几何。
然后我们在drawGeometry()
中修补了OpenLayers.Renderer.Elements
函数来绘制这个新几何体:
OpenLayers.Util.extend(OpenLayers.Renderer.Elements.prototype, {
drawGeometry: function (geometry, style, featureId) {
var cl = geometry.CLASS_NAME;
var rendered = true,
i, len;
if ((cl === "OpenLayers.Geometry.Collection") ||
(cl === "OpenLayers.Geometry.MultiPoint") ||
(cl === "OpenLayers.Geometry.MultiLineString") ||
(cl === "OpenLayers.Geometry.MultiPolygon") ||
(cl === "YourApp.Geometry.EndPointsPath")) {
// Iterate over all Geometry components and draw each individually
for (i = 0, len = geometry.components.length; i < len; i++) {
// Is there a style for each of the components?
if (OpenLayers.Util.isArray(style)) {
// Draw Geometry with own style
rendered = this.drawGeometry(geometry.components[i], style[i], featureId) && rendered;
} else {
// Draw Geometry with common style
rendered = this.drawGeometry(geometry.components[i], style, featureId) && rendered;
}
}
return rendered;
}
// (...standard code...)
},
eraseGeometry: function (geometry, featureId) {
var cl = geometry.CLASS_NAME,
i, len;
if ((cl === "OpenLayers.Geometry.MultiPoint") ||
(cl === "OpenLayers.Geometry.MultiLineString") ||
(cl === "OpenLayers.Geometry.MultiPolygon") ||
(cl === "YourApp.Geometry.EndPointsPath") ||
(cl === "OpenLayers.Geometry.Collection")) {
for (i = 0, len = geometry.components.length; i < len; i++) {
this.eraseGeometry(geometry.components[i], featureId);
}
// (...standard code...)
}
}
});
答案 1 :(得分:1)
据我所知,要获得此功能,您需要使用自己的扩展类。
首先创建OpenLayers.Feature.Vector的扩展,将其命名为YourApp.Feature.MultiVector。您可以通过查看OpenLayers代码来查看有关如何扩展类的示例。该类应该接受样式数组和multiPolygon。它应该有一个方法,它将返回一个OpenLayers.Feature.Vectors列表,每个都有自己的样式。
再次创建OpenLayers.Layer.Vector的扩展,将其命名为YourApp.Layer.VectorSupportingMultiStyledFeatures。您需要覆盖“drawFeature”方法。在drawFeature方法测试中,查看特征的类型是否为MultiVector。如果是,则遍历MultiVector中的每个要素并调用renderer.drawFeature(feature)。否则调用super.drawFeature方法。
所以你调用它的代码看起来像这样:
var multiPol = new YourApp.Feature.MultiVector(
new OpenLayers.Geometry.MultiPolygon([polygonGeometry1,polygonGeometry2]),
[style1,style2,style3,style4]);
var layer = new YourApp.Layer.VectorSupportingMultiStyledFeatures("polygonLayer");
layer.addFeatures([multiPol]);