I’m trying to get a regular form field used for searching for an address to autocomplete its values, as seen on this page, using Leaflet Geosearch plugin.
So far the documentation says it can be binded to a form. Jquery UI’s autocomplete looks like it can accomplish this, however i have not been able to wrap my head around how to do it.
I have successfully linked the form field to the geosearch provider, and it returns an array that can be seen in the browser console. I can algo get the autocomplete plugin to work, but with a local array, not the one produced by the geosearch plugin.
Here is an example of both plugins in action separately:
<!DOCTYPE html> <html> <head> <title>Leaflet tests</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css"> <script src="https://code.jquery.com/jquery-3.6.0.js"></script> <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"/> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <style type="text/css"> #mapid { height: 500px; width: 500px}</style> <link rel="stylesheet" href="https://unpkg.com/leaflet-geosearch@3.0.0/dist/geosearch.css" /> <script src="https://unpkg.com/leaflet-geosearch@3.0.0/dist/geosearch.umd.js"></script> </head> <body> <div id="mapid"></div> <hr> <div class=""> <label for="search">geosearch field (check console): </label> <input id="search"> </div> <div class=""> <label for="search2">autocomplete field (apple or banana): </label> <input id="search2"> </div> <script type="text/javascript"> //code for generating map below var mymap = L.map('mapid').setView([51.505, -0.09], 13); L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>', subdomains: ['a','b','c'] }).addTo(mymap); //code for search form below const providerform = new GeoSearch.OpenStreetMapProvider(); const input = document.querySelector('input[id="search"]'); input.addEventListener('input', async (event) => { const results = await providerform.search({ query: input.value }); console.log(results[0]); // ยป [{}, {}, {}, ...] }); // let fruits = ['Apple', 'Banana'] $("#search2").autocomplete( { source: fruits, delay: 100, minLength: 1 }); </script> </body> </html>
I’d greatly appreciate any pointers in the right direction on how to get the autocomplete to work with the geosearch provider.
Advertisement
Answer
This should work, but I don’t know how to check at the moment because https://nominatim.openstreetmap.org/ is currently not working.
$('#search2').autocomplete({ source(request, response) { const providerform = new GeoSearch.OpenStreetMapProvider({ params: { limit: 5 } }); return providerform.search({ query: request.term }).then(function (results) { response(results); }); }, delay: 100, minLength: 1 });