我想用数据填充GeoJson图层,然后动态过滤要显示的功能。
我已经使用了过滤功能,但我不知道如何更改过滤器然后刷新图层。
添加数据后,有什么方法可以更新过滤器吗?
答案 0 :(得分:16)
我是通过根据功能的属性将每种要素类型添加到其他LayerGroup来实现此目的的。 e.g。
以GeoJSON
var data =[
{
type: "Feature",
properties: {
type: "type1"
},
geometry: {
type: "Point",
coordinates: [-1.252,52.107]
}
},
{
type: "Feature",
properties: {
type: "type2"
},
geometry: {
type: "Point",
coordinates: [-2.252,54.107]
}
}
];
创建GeoJSON图层
//array to store layers for each feature type
var mapLayerGroups = [];
//draw GEOJSON - don't add the GEOJSON layer to the map here
L.geoJson(data, {onEachFeature: onEachFeature})//.addTo(map);
/*
*for all features create a layerGroup for each feature type and add the feature to the layerGroup
*/
function onEachFeature(feature, featureLayer) {
//does layerGroup already exist? if not create it and add to map
var lg = mapLayerGroups[feature.properties.type];
if (lg === undefined) {
lg = new L.layerGroup();
//add the layer to the map
lg.addTo(map);
//store layer
mapLayerGroups[feature.properties.type] = lg;
}
//add the feature to the layer
lg.addLayer(featureLayer);
}
然后你可以调用Leaflet map.addLayer/removeLayer函数,例如
//Show layerGroup with feature of "type1"
showLayer("type1");
/*
* show/hide layerGroup
*/
function showLayer(id) {
var lg = mapLayerGroups[id];
map.addLayer(lg);
}
function hideLayer(id) {
var lg = mapLayerGroups[id];
map.removeLayer(lg);
}
答案 1 :(得分:1)
在GeoJSON addData
方法中,首先检查数据是否是要素的集合,在这种情况下,为每个要素调用方法。
然后按如下方式应用过滤器:
var options = this.options;
if (options.filter && !options.filter(geojson)) { return; }
因此,如果过滤器在添加数据时过滤掉数据,则不会在任何地方存储或记住数据。更改过滤器不会突然重新出现数据。
您可以保留对geojson的引用,并在更改过滤器时重新初始化图层。
答案 2 :(得分:0)
见下面的例子,你有一张地图和一个myBus图层。
map.removeLayer(myBus);
...add your data edit something ...
myBus.addTo(map);