OpenLayers 3根据属性选择并高亮feature
OpenLayers 3 版本:OpenLayers v4.3.2
想通过属性查询feature,但是在ol3中并没有发现类似ol2中的getFeatureByAttribute()....
自己写函数实现,实现方法如下:
var layer = new ol.layer.Vector({ source: new ol.source.Vector({ features:ol.Feature, url: './resources/data/test.geojson', format: new ol.format.GeoJSON() }), style:polygonStyle }); map.addLayer(layer);
function selectByAttribute(){ var features = layer.getSource().getFeatures(); //console.log(features); var value = '115街坊'; var property = 'name';
var selectedByAttriFeature;//实际应用中设置成全局变量 for (var i = 0, ii = features.length; i < ii; i++) { if (features[i].get(property) === value) { selectedByAttriFeature = features[i]; break; } } selectedByAttriFeature.setStyle(featureSelectStyle);//高亮查询到的feature //console.log(selectedByAttriFeature.getGeometry().A);//后台输出发现,geometry属性中有一个属性A其实是中心点坐标,但是没有提供获取中心点的方法,.getGeometry().A也可获得中心点 //console.log(getCenterOfExtent(selectedByAttriFeature.getGeometry().getExtent()));//结果同上 var my_view = new ol.View({ center: getCenterOfExtent(selectedByAttriFeature.getGeometry().getExtent()), zoom: 14 }); map.setView(my_view); }
获得feature的中心点坐标:【偶然发现ol3有方法获得中心点坐标:ol.extent.getCenter(selectedFeature.getGeometry().getExtent())】
function getCenterOfExtent(Extent){ var X = Extent[0] + (Extent[2]-Extent[0])/2; var Y = Extent[1] + (Extent[3]-Extent[1])/2; return [X, Y]; }
清除已经选择的高亮feature:
function clearSelectByAttribute(){ if(selectedByAttriFeature != null){ selectedByAttriFeature.setStyle(null); selectedByAttriFeature = null; } }