我有一张地图,其中包含通过 AJAX 从 GeoJSON 导入的大量标记,但我无法进行过滤。
有 3 个复选框,可以选中它们的任意组合。每个标记都有一个名为“类型”的属性,可以包含 3 个值的任意组合(它是可能有软饮料、勺子和/或奶昔的商店地图,因此“软勺奶昔”、“软勺”、“轻摇”、“舀摇”、“舀”、“摇”)。
第一行
==
工作正常,但是当我尝试 indexOf()
或 search()
风格的东西时,一切都崩溃了,根本没有加载。
我也尝试过使用数组,但是 Leaflet 的过滤器部分没有得到很好的描述,而且 JavaScript 也不是我的“第一语言”。
var geojsonLayer = new L.GeoJSON.AJAX("data/map.geojson", {
pointToLayer: pointToLayer,
filter: icefilter
});
function icefilter(json) {
var icetypeFilter = "";
var cond1 = true;
$("input[name=icetype]").each(function () {
if (this.checked) {
icetypeFilter = icetypeFilter + " " + this.value;
}
});
var att = json.properties.types;
if (icetypeFilter.length == 0) {
cond1 = true;
} else if (att == " soft scoop shake") {
cond1 = true;
} else {
cond1 = att == icetypeFilter; //Works fine with this one
//cond1 = att.indexOf(icetypeFilter) >= 0; //The moment I activate this line and remove the one above everything is broken and no markers are shown - even with no filters selected.
}
return cond1;
}
$("input[name=icetype]").click(function () {
clusterLayer.clearLayers();
geojsonLayer.refresh();
locationList();
});
IIUC,您想用 3 个复选框实现 AND 过滤器。您的 GeoJSON 数据包含具有
properties.types
字段的要素,作为 " soft scoop shake"
形式的字符串(可能包含较少的单词)。
cond1 = att.indexOf(icetypeFilter) >= 0;
当我激活这条线的那一刻[...]一切都被破坏了并且没有显示任何标记 - 即使没有选择过滤器。
可能发生的情况是您的某些功能缺少
properties.types
字段。所以 att
是 undefined
,并且 att.indexOf()
会引发错误并停止脚本(与任何其他方法调用相同,例如 att.search()
。
“立即”解决方案可能包括确保始终将
att
变量作为字符串:
var att = json.properties.types;
if (typeof att !== "string") {
att = ""; // Ensure we always have a string
}
话虽这么说,如果
properties.types
并不总是以相同的顺序列出单词,或者如果您不以完全相同的顺序循环检查复选框,您将会遇到麻烦。
例如功能可以有
" shake scoop"
类型,但复选框要求 " scoop shake"
。
您不应该将复选框值连接在字符串中,因为它会强制执行某些可能与您的功能不完全匹配的顺序,即使它们具有正确的单词(但顺序不同)。
填充数组,你可以这样做:
var icetypeFilter = []; // Use an array
$("input[name=icetype]").each(function () {
if (this.checked) {
icetypeFilter.push(icetypeFilter + " " + this.value);
}
});
// ...
return icetypeFilter.every(checkValue => att?.contains(checkValue));
.every()
方法:
就像数学中的“for all”量词。特别是,对于空数组,它返回every
。true
所以它可以取代您的 3 张支票。
然后您可以稍后通过使用正则表达式等进行改进