smeijer / leaflet-geosearch

A geocoding/address-lookup library supporting various api providers.
https://smeijer.github.io/leaflet-geosearch/
MIT License
1.02k stars 270 forks source link

method call on marker click #354

Open Khodor1997 opened 1 year ago

Khodor1997 commented 1 year ago

Is it possible to implement marker click events after a search to call a custom function? Please advise how this can be done. Using vue2 Thanks

ahmedkhairydev commented 1 year ago

I have built my custom workaround to do that.

First, Add the search control to your map.

const searchControl = SearchControl({
  style: "bar",
  marker: {
    opacity: 0,
  },
  provider: new OpenStreetMapProvider(),
  autoCompleteDelay: 500,
  autoClose: true,
});

map.addControl(searchControl);

// popupopen logic
searchControl.markers.on("popupopen", () => {
  // enter your custom logic here...
});

Second, Add the keydown event listener to get the selected result option when the user presses Enter in the search input.

searchControl.searchElement.input.addEventListener("keydown", (event) => {
  const ENTER_KEY = "Enter",
    results = searchControl.resultList.results,
    inputValue = event.target["value"];

  if (event.key === ENTER_KEY && results.length) {
    // check if the user chooses an option from the results by the keyboard arrows
    if (results.find((result) => result.label === inputValue)) {
      getTheSelectedOption(
        results.findIndex((result) => result.label === inputValue)
      );
    } else {
      // choose the first option of the results in case the user pressed `Enter` without marking any option by the keyboard arrows
      getTheSelectedOption();
    }
  }
});

Third, Add the click event listener to get the selected option.

searchControl.resultList.container.addEventListener("click", (event) => {
  const itemIndex = +(event.target as HTMLElement).getAttribute(
    "data-key"
  );
  getTheSelectedOption(itemIndex);
});

Finally, Add the getTheSelectedOption function which you should write your custom logic inside it.

const getTheSelectedOption = (itemIndex = 0) => {
  const item = searchControl.resultList.results[itemIndex];

  // enter your custom logic here...
};

I hope this will help you.

ahmedkhairydev commented 1 year ago

@Khodor1997

I found this event also, map.on('geosearch/showlocation', yourEventHandler);