Leaflet Search Filter only exact matches

569 views Asked by At

I'm using Leaflet Search and Fuse.js to search multiple leaflet layers and multiple feature.properties in each one. I've finally got the code working (but it is really messy). Only issue is that because I'm using filterData it is showing ALL markers when I search anything instead of exact matches.

Any way to show exact matches only?

var fuseOptions = {
  shouldSort: true,
  tokenize: true,
  threshold: 0,
  location: 0,
  maxPatternLength: 32,
  minMatchCharLength: 2,
  keys: ['properties.myKey']
};

    var fuse = new Fuse(city.features.concat(village.features.concat(gateway.features.concat(trade.features.concat(danger.features.concat(connect.features.concat(forest.features.concat(mine.features.concat(office.features.concat(farm.features.concat(fish.features.concat(annex.features)))))))))), fuseOptions), {
        keys: [
            'properties.name',
            'properties.prod1',
            'properties.extraprod1',
            'properties.extraprod2',
            'properties.extraprod3',
            'properties.extraprod4',
            'properties.extraprod5',
            'properties.buff',
            //'properties.operator'
        ]
    });
    L.control.search({
           initial: false,
           layer: allLayers,
           collapsed: false,
           casesensitive: false,
           propertyName: 'name',
           container: 'findbox',
       filterData: function(text, records) {
            var jsons = fuse.search(text),
                ret = {}, key;
            
            for(var i in jsons) {
                key = jsons[i].properties.name;
                ret[ key ]= records[key];
            }

            console.log(jsons,ret);
            return ret;
        }
    })
    .on('search:locationfound', function(e) {
        e.layer.openPopup();
    })
    .addTo(map);
1

There are 1 answers

6
Falke Design On

I'm not sure if this work but try:

filterData: function(text, records) {
            var jsons = fuse.search(text),
                ret = {}, key;
            
            for(var i in jsons) {
                key = jsons[i].properties.name;
                if(key.startsWith(text)){
                    ret[ key ]= records[key];
                }
                // Try with and without this line
                else { rect[key] = null; }
            }

            console.log(jsons,ret);
            return ret;
        }