为什么我的Leaflet过滤不能与indexOf()或search()一起使用?

问题描述 投票:0回答:1

我有一张地图,其中包含通过 ajax 从 geojson 导入的大量标记,但我无法进行过滤。

有 3 个复选框,可以选中它们的任意组合。每个标记都有一个称为“类型”的属性,它可以包含 3 个值的任意组合。 (这是一张可能有软饮料、勺子和/或奶昔的商店地图,所以“软勺奶昔”、“软勺”、“软奶昔”、“勺奶昔”、“勺”、“奶昔”)

  1. 首先我检查哪些值被检查并将它们添加到一个字符串中。
  2. 然后我检查是否没有检查,如果是,则应显示所有标记。
  3. 然后我检查标记是否具有全部 3 个值,在这种情况下它应该始终显示(因为它满足所有值)。
  4. 最后我检查特定的选定值是否在标记上。如果完全相同,则效果很好,但如果选项 3 是唯一选定的值,并且标记同时具有选项 2 和 3,则仍应显示。

第一行

==
工作正常,但当我尝试
indexOf()
search()
风格的东西时,一切都会崩溃,根本没有加载。

我也尝试过使用数组,但传单的过滤器部分没有得到很好的描述,并且 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 show - even with no filters selected.  
  }
  return cond1;
}

$("input[name=icetype]").click(function () {
  clusterLayer.clearLayers();
  geojsonLayer.refresh();
  locationList();
});
jquery filter leaflet
1个回答
0
投票

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()
方法:

every
就像数学中的“for all”量词。特别是,对于空数组,它返回
true

所以它可以取代您的 3 张支票。


然后您可以稍后通过使用正则表达式等进行改进

© www.soinside.com 2019 - 2024. All rights reserved.