128
128
< script
129
129
src ="https://unpkg.com/protomaps-leaflet/dist/protomaps-leaflet.js "
130
130
> </ script >
131
+ < script src ="
https://unpkg.com/[email protected] "
> </ script >
131
132
132
133
< link rel ="preconnect " href ="https://unpkg.com ">
133
134
< link rel ="preconnect " href ="https://api.protomaps.com ">
@@ -848,18 +849,40 @@ <h3>Loading Error</h3>
848
849
// Cities search functionality
849
850
let citiesData = [ ] ;
850
851
let searchTimeout = null ;
852
+ let fuse = null ;
851
853
852
854
// Load cities data
853
855
async function loadCitiesData ( ) {
854
856
try {
855
857
const response = await fetch (
856
- "https://unpkg.com/[email protected] /cities.json" ,
858
+ "https://unpkg.com/[email protected] /cities.json"
857
859
) ;
858
860
citiesData = await response . json ( ) ;
861
+
862
+ // Initialize Fuse instance with loaded data
863
+ fuse = new Fuse ( citiesData , {
864
+ keys : [
865
+ { name : 'name' , weight : 2 } , // Give more weight to city name
866
+ { name : 'country' , weight : 0.3 } // Also search by country but with lower weight
867
+ ] ,
868
+ includeScore : true ,
869
+ threshold : 0.4 , // Slightly more lenient threshold
870
+ distance : 100 , // Allow more errors for longer strings
871
+ minMatchCharLength : 2 ,
872
+ shouldSort : true , // Ensure results are sorted by score
873
+ ignoreLocation : true , // Ignore where the match occurs in the string
874
+ useExtendedSearch : true , // Enable extended search features
875
+ getFn : ( obj , path ) => {
876
+ // Custom getter to handle both exact and fuzzy matches
877
+ const value = Fuse . config . getFn ( obj , path ) ;
878
+ return typeof value === 'string' ? value . normalize ( 'NFD' ) . replace ( / [ \u0300 - \u036f ] / g, '' ) : value ;
879
+ }
880
+ } ) ;
881
+
859
882
console . log (
860
883
"Cities data loaded:" ,
861
884
citiesData . length ,
862
- "cities" ,
885
+ "cities"
863
886
) ;
864
887
} catch ( error ) {
865
888
console . error ( "Error loading cities data:" , error ) ;
@@ -869,14 +892,14 @@ <h3>Loading Error</h3>
869
892
870
893
// Search cities function
871
894
function searchCities ( query ) {
872
- if ( ! query || query . length < 2 ) {
895
+ if ( ! query || query . length < 2 || ! fuse ) {
873
896
return [ ] ;
874
897
}
875
898
876
- query = query . toLowerCase ( ) ;
877
- return citiesData
878
- . filter ( ( city ) => city . name . toLowerCase ( ) . includes ( query ) )
879
- . slice ( 0 , 10 ) ; // Limit to 10 results
899
+ const results = fuse . search ( query ) ;
900
+ return results
901
+ . slice ( 0 , 10 ) // Limit to 10 results
902
+ . map ( result => result . item ) ;
880
903
}
881
904
882
905
// Display search results
0 commit comments