Leaflet GeoApiFrProvider Sending Incomplete Search Requests

119 views Asked by At

I am working on a map application using Leaflet and the GeoApiFrProvider. While the setup works correctly most of the time, I'm encountering an issue where the search request is sent prematurely, before I've had the chance to complete the full address. Specifically, if the address starts with the digit "1," the search request is triggered with just "1," resulting in an incomplete and inaccurate search request. This causes issues with the following API call: GET https://api-adresse.data.gouv.fr/search?q=1

How can I modify the behavior of the GeoApiFrProvider to ensure that it waits for the complete address query before sending the search request?

    const searchControl = new GeoSearchControl({
        //provider: new OpenStreetMapProvider(),
        provider: new GeoApiFrProvider(
        {
        searchUrl: 'https://api-adresse.data.gouv.fr/search',
        reverseUrl: 'https://api-adresse.data.gouv.fr/reverse'
        }
        ),
        style: 'bar',
        keepResult: true,
        showPopup: false,
        notFoundMessage: "aucun élément trouvé",


        marker: {
            icon
        },
        searchLabel: 'Entrer une adresse'
    });
    
    if (marker !== undefined) {
        map.removeLayer(marker);
    }
    
    map.addControl(searchControl);

enter image description here

1

There are 1 answers

0
init-qy On

You can rewrite the function search:

const search = async function ({ query }) {
  if (query.length < 3) return [];
  else if (query.length > 200) query = query.substring(0, 200);

  const url = this.endpoint({
    query: query,
    type: 0
  });

  const request = await fetch(url);
  const json = await request.json();
  return this.parse({ data: json });
};
const provider = new GeoApiFrProvider({
  searchUrl: "https://api-adresse.data.gouv.fr/search",
  reverseUrl: "https://api-adresse.data.gouv.fr/reverse"
});
provider.search = search;

The full demo: https://codepen.io/init-qy/pen/ExGJvyo