Giter VIP home page Giter VIP logo

leaflet.autocomplete's Introduction

Leaflet.Autocomplete GeoSearch outside map

Leaflet.Autocomplete is to expand the autocomplete plugin with the ability to geocode and show data on the map in the way you think you need

This example uses remote api for geocoding NOMINATIM-API in GeoJSON format and is based on the library AUTOCOMPLETE

Demo

See the demo - example

You can also use the autocomplete library on a map, see this example: autocomplete-on-map

Features

  • Use remote api or static files, e.g. in the GeoJSON format, but there is nothing to prevent it from being a different format.
  • Accessible, with full support for ARIA attributes and keyboard interactions.
  • Customize your own CSS.
  • Support for asynchronous data fetching.
  • Move between the records using the arrows , and confirm by Enter
  • No dependencies

Usage

HTML

<div class="auto-search-wrapper">
  <input
    type="text"
    autocomplete="off"
    id="search"
    class="full-width"
    placeholder="enter the city name"
  />
</div>

CSS

<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/gh/tomickigrzegorz/[email protected]/dist/css/autocomplete.min.css"
/>

JS

<script src="https://cdn.jsdelivr.net/gh/tomickigrzegorz/[email protected]/dist/js/autocomplete.min.js"></script>

JS for AUTOCOMPLETE

All parameters controlling the AUTOCOMPLETE library available on this page https://tomickigrzegorz.github.io/autocomplete/

// minimal configure
new Autocomplete("search", {
  // default selects the first item in
  // the list of results
  selectFirst: true,

  // The number of characters entered should start searching
  howManyCharacters: 2,

  // onSearch
  onSearch: ({ currentValue }) => {
    // You can also use static files
    // const api = '../static/search.json'
    const api = `https://nominatim.openstreetmap.org/search?format=geojson&limit=5&city=${encodeURI(
      currentValue
    )}`;

    /**
     * jquery
     */
    // return $.ajax({
    //     url: api,
    //     method: 'GET',
    //   })
    //   .done(function (data) {
    //     return data
    //   })
    //   .fail(function (xhr) {
    //     console.error(xhr);
    //   });

    // OR -------------------------------

    /**
     * axios
     * If you want to use axios you have to add the
     * axios library to head html
     * https://cdnjs.com/libraries/axios
     */
    // return axios.get(api)
    //   .then((response) => {
    //     return response.data;
    //   })
    //   .catch(error => {
    //     console.log(error);
    //   });

    // OR -------------------------------

    /**
     * Promise
     */
    return new Promise((resolve) => {
      fetch(api)
        .then((response) => response.json())
        .then((data) => {
          resolve(data.features);
        })
        .catch((error) => {
          console.error(error);
        });
    });
  },
  // nominatim GeoJSON format parse this part turns json into the list of
  // records that appears when you type.
  onResults: ({ currentValue, matches, template }) => {
    const regex = new RegExp(currentValue, "gi");

    // if the result returns 0 we
    // show the no results element
    return matches === 0
      ? template
      : matches
          .map((element) => {
            return `
          <li class="loupe">
            <p>
              ${element.properties.display_name.replace(
                regex,
                (str) => `<b>${str}</b>`
              )}
            </p>
          </li> `;
          })
          .join("");
  },

  // we add an action to enter or click
  onSubmit: ({ object }) => {
    // remove all layers from the map
    map.eachLayer(function (layer) {
      if (!!layer.toGeoJSON) {
        map.removeLayer(layer);
      }
    });

    const { display_name } = object.properties;
    const [lng, lat] = object.geometry.coordinates;

    const marker = L.marker([lat, lng], {
      title: display_name,
    });

    marker.addTo(map).bindPopup(display_name);

    map.setView([lat, lng], 8);
  },

  // get index and data from li element after
  // hovering over li with the mouse or using
  // arrow keys ↓ | ↑
  onSelectedItem: ({ index, element, object }) => {
    console.log("onSelectedItem:", index, element, object);
  },

  // the method presents no results element
  noResults: ({ currentValue, template }) =>
    template(`<li>No results found: "${currentValue}"</li>`),
});

MAP initialization

const config = {
  minZoom: 6,
  maxZomm: 18,
};
// magnification with which the map will start
const zoom = 3;

// coordinates
const lat = 52.22977;
const lng = 21.01178;

// calling map
const map = L.map("map", config).setView([lat, lng], zoom);

// Used to load and display tile layers on the map
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution:
    '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map);

Other options

This example geocodes addresses, but nothing prevents you from showing polygons or other things on the map. You can use the same library for other purposes.


Autocomplete on the map

A bit of work and you can put this functionality on the map, see an example: autocomplete-on-map-button


Multi-layer search

You can also search in layers using this library: multi-layer-search. Each color reflects a separate layer. In the example, there are exactly three layers - restaurant, bar and pharmacy.


Autocomplete with geojson

You can also search in FeatureCollection: autocomplete-with-geojson

leaflet.autocomplete's People

Contributors

olivier3lanc avatar tomickigrzegorz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

leaflet.autocomplete's Issues

How to hide 'not matched item' in the result list.

Thank you for providing the excellent search functionality. I have a question that requires your assistance.
Please visit the webpage http://route.capas.oome.net/sharecode/Leaflet.Autocomplete-master/docs/index.html. I have used the code from this repository and run the docs/index.html file, with only modifications script.js file onlines 8-14 of the , changing the data source from api to the built-in search.json file.
When I search for "gmina," all 10 results are listed in the list, with 3 of them not matched "gmina".
Since my own geojson file contains thousands of data entries, I do not wish to display all the items. Instead, I would like to display only the entries that match the search keyword, as shown in the image.
Snipaste_2024-04-17_21-23-39
How should I modify the JavaScript code ?

Not reset settings

No settings reset after clicking the 'x' button. Search results are also not closed.

Remove address list

Hi,

how remove address list, when I clear input field by keypress backspace?

There is a typo "maxZomm"

First of all, great job!

There is a typo in the code. Search for maxZomm. Should be maxZoom, obviously.

How to inicialize clearButton (x) when the field comes with default value

Hi Tomas,

now, the clearButton is displayed only when the value is supplied for the input over autocomplete. What is great for post add.

On post edit, the field comes already with the value and there is no clearButton. Can you add detection if the autocomplete field has default value so clearButton is displayed automatically?

An issue that's not really an issue...

Hello, and thank you for creating such a lovely tool! I am wondering if you might be willing to share an unminified version of autosuggest.js just to help with debugging? I have been experiencing some oddness with returns that I would like to get to the bottom of. All the best.

Violating Nominatim Usage Policy

According to https://operations.osmfoundation.org/policies/nominatim/ :

Unacceptable Use
The following uses are strictly forbidden and will get you banned:

  • Auto-complete search This is not yet supported by Nominatim and you must not implement such a service on the client side using the API.
    ...

It seems to me that your repo violates Nominatim usage policy by providing client-side autocomplete using Nominatim API. I would propose using other public APIs like https://photon.komoot.io instead in order to stick with fair use.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.