leaflet-geosearch icon indicating copy to clipboard operation
leaflet-geosearch copied to clipboard

Adding a function to get the Location of the selected result

Open SalahAdDin opened this issue 2 years ago • 1 comments

Thanks for this greap library, we could replace react-leaflet-search with this library.

Something is missing: we want to get the location from the selected result.

Right now we do it by a fired event(geosearch/showlocation) as follows:

const LeafLetGeoSearch = ({
  onLocationResult,
}: {
  onLocationResult: (latLng: GeometryT) => void;
}) => {
  const provider = new OpenStreetMapProvider();

  const controlOptions = {
    provider,
    style: 'bar',
    autoClose: true,
    keepResult: true,
    zoomLevel: 7,
  };

  const searchControl: Control = GeoSearchControl(controlOptions);

  const map = useMap();

  // TODO: Handle it to be settled up once
  map.on('geosearch/showlocation', (result) => {
    if (result) {
      const {
        location: { x, y },
      } = result as LeafletEvent & { location: SearchResult };

      onLocationResult({ lat: x, lng: y });
    }
  });

  useEffect(() => {
    map.addControl(searchControl);

    return () => {
      map.removeControl(searchControl);
    };
  }, []);

  return null;
};

The problem with this approaching is the event is fired many times, and it can affect the render performance: Screen Shot 2022-06-18 at 00 46 19

The aforementioned library uses a callback(onChange) to handle it.

What's about using a kind of function to get it?

Thank you

SalahAdDin avatar Jun 17 '22 21:06 SalahAdDin

The function fires many times because you should use map.on inside useEffect, as it behaves like addEventlistener.

So something like:


  const onShowLocation = (result: LeafletEvent) => {
    if (result) {
   // read location here
    }
  };

  useEffect(() => {
    map.addControl(searchControl);

    map.on('geosearch/showlocation', onShowLocation);

    return () => {
      map.removeControl(searchControl);

      map.off('geosearch/showlocation', onShowLocation);
    };
  }, []);

...```

cyango avatar Aug 24 '22 11:08 cyango