I’ve long tried to implement this feature for my map system, because I have lots of markers loaded in and it’s very useful to be able to enter a string such as “abc” into an input field to “filter out” (visually hide) all the ones that don’t contain that string inside of their description/title.
A few weeks ago, I found this example: https://docs.mapbox.com/mapbox-gl-js/example/filter-markers/
Unfortunately, they do it in a completely silly manner which doesn’t apply to my situation, so I was only able to grab the basic input part from their example. Then I got stuck. I tried countless things and after many hours of work, I at least have finally managed to be able to loop through my loaded-in geoJson “sources” (containing all the markers). So, I have this:
filterInput.addEventListener('keyup', (e) =>
{
const value = e.target.value.trim().toLowerCase();
let sources = Object.entries(map.getStyle().sources);
for (const source of sources)
{
if (source[1].type == 'geojson')
{
console.log(source[0]); // The name of the source, for example "my nostalgic visited places".
// Here, I'm trying to loop through all the inidividual markers of this geoJson "source" and, based on "value" and its title/description, either visually hide or display it. This is the part I just cannot figure out.
}
}
});
I obviously need to loop through the markers inside each geoJson inside my sources for loop, but how? I don’t know:
- How to actually loop through those in the first place. I can’t find any in the source object.
- How to tell MapBox GL JS to hide/show them individually. The example that they have just bulk hide/show entire layers/sources, which is irrelevant.
If it helps, console.log(source[1]);
causes this kind of output:
{type: 'geojson', data: 'http://127.0.0.1/mymap/geoJSON/my nostalgic visited places.geojson'}
data: "http://127.0.0.1/mymap/geoJSON/my nostalgic visited places.geojson"
type: "geojson"
[[Prototype]]: Object
Disappointingly, the [[Prototype]]: Object
does not seem to contain any neat array of markers, as I first assumed would be the case. I don’t know what to make of it.