我在OpenLayers 3中遇到了一件非常奇怪的事情,也许有人可以帮我解决这个问题。我试图使用以下函数基于坐标数组在地图上显示多边形:
Map.prototype.addLocation = function(location) {
var polygon, i, z;
if (typeof location.geometry === 'undefined') return false;
for (i = 0; i < location.geometry.length; i++) {
for (z=0; z < location.geometry[i].length; z++) location.geometry[i][z]=this.transformProjection(location.geometry[i][z]);
}
polygon=this.createFeature('polygon', 'location', location.geometry);
polygon.values_.content.push(location.data);
this.map.getView().fit(polygon.getGeometry().getExtent(), this.map.getSize());
}
Map.prototype.createFeature = function(type, group, geometry, layer) {
var _geometry, feature;
if (typeof layer == 'undefined') layer='main';
if (type == 'polygon') _geometry=new ol.geom.Polygon(geometry);
else if (type == 'point') _geometry=new ol.geom.Point(geometry);
else return false;
this.features.entities++;
feature=new ol.Feature({
geometry: _geometry,
type: type,
group: group,
state: 0,
content: []
});
feature.setId(this.features.entities);
feature.setStyle(this.styles[type][group].default);
this.layers[layer].getSource().addFeature(feature);
this.features[type][group].push(feature);
return feature;
}
Map.prototype.transformProjection = function(coordinates, from, to) {
if (typeof from == 'undefined') from = 'EPSG:4326';
if (typeof to == 'undefined') to = 'EPSG:3857';
return ol.proj.transform(coordinates, from, to);
}
基本上,这里发生的是Map.addLocation
被调用,参数设置为一个对象,它具有geometry
属性,包含一个坐标数组。它应该将坐标从lat / lon转换为OL3使用的投影,将该特征添加到默认基本图层,然后尝试将多边形拟合到地图div的视口中。发生的事情真的很奇怪:
如果我按原样保留代码,则会渲染地图,但不会在其上绘制多边形,也不会出现Javascript错误。但是,如果我将this.map.getView().fit()
方法参数更改为无效的内容(例如,更改为this.map.getView().fit(polygon, this.map.getSize());
),则会渲染地图,在地图上绘制多边形,并出现错误: AssertionError :断言失败:无效范围或几何。如果我完全删除该行,则不会出现错误,但无论如何都不会绘制多边形。
我无法弄清楚导致这种情况的原因,好像我正确使用this.map.getView().fit()
方法,我没有得到任何错误,但我也没有得到所需的结果。如果我错误地使用它,我会得到所需的结果,但是出现的错误会导致我的代码中的所有内容无效。有什么想法会发生什么?