摘要:
任务是ol3图层中选定矢量图层下载到本地,保存为GeoJson文件。
本文分为如下2部分
- 整个矢量图层下载
- 指定多边形范围下载
- 多边形区域下载存在的问题
var geoJsonObject = new ol.format.GeoJSON().writeFeatures(layer.getSource().getFeatures());
var data = "text/json;charset=utf-8," + encodeURIComponent(geoJsonObject);
$("#btn-download").attr('href','data:' + data);
$("#btn-download").attr('download',downloadLayerName + '.geoJson');
这里前两句是构造数据,后两句是把数据绑定到一个按钮之上,让这个按钮变成一个下载按钮,实现效果如下图:

ids = new Array();实现的效果图如下: 先划定区域选中区域多边形,
multiPoly = new ol.geom.MultiPolygon();
select.getFeatures().forEach(function(feature){
ids.push(feature.getId());
geom = feature.getGeometry()
if(geom instanceof ol.geom.Polygon){
multiPoly.appendPolygon(geom);
}
else{
alert("You must select only Polygons!!");
return;
}
features = new Array();
map.getLayers().forEach(function(layer){
if(layer instanceof ol.layer.Vector){
if(layer.get('visible')){
layer.getSource().getFeatures().forEach(function(feature){
if(multiPoly.intersectsExtent(feature.getGeometry().getExtent())){
if($.inArray(feature.getId(), ids) == -1){
features.push(feature);
}
}
})
}
}
})

再点击下载按钮:

三、存在的问题 intersectsExtent函数计算的是要素的外包范围,并不是准确的范围,这样对于点来说是对的但是对于线和面就不对了,因为线和面的外包范围和其真实的边界并不重合,如下图所示:

这种情况下我们需要自己写代码来计算范围多边形与要素多边形的拓扑关系,*其实别人已经造好了,我们只需要使用就可以了,其中可以用的包括:TURF.js 和JSTS,暂时还没有实现,可以参开http://*.com/questions/35386689/polygon-selection-openlayers-3 欢迎交流,完。