Openlayers 3过滤加载geojson数据/逐条加载数据,并赋予属性
近日有需求在openlayers 3中加载geojson数据,只加载指定属性值得部分。
解决方法:
(1)ajax请求geojson数据
(2)逐条判断属性值,满足条件的创建geometry
(3)满足条件的创建feature并赋予属性
(4)将所有满足条件的features加入vector Layer
代码如下:
function addFeaturesByAttributes(){ var myurl = "./resources/data/01.geojson"; var source = new ol.source.Vector(); $.ajax({ url: myurl, type: "GET",//请求方式为get dataType: "json", //返回数据格式为json async: false,//设置ajax为同步请求, 默认为异步 success: function(data) { for(var i =0;i<data.features.length;i++){ if(data.features[i].properties.group == 4){//此处加载过滤条件,group为4的添加到图层中 var coords = data.features[i].geometry.coordinates; var geom = new ol.geom.Point(ol.proj.transform(coords, 'EPSG:4326', 'EPSG:3857')); var feature = new ol.Feature(geom); feature.setProperties({"name":"test","value":"test_value"});//为每个feature增加属性字段及值 source.addFeature(feature); } } } }).responseText; var vector = new ol.layer.Vector({ source: source, style:testStyleFunction }); map.addLayer(vector); }