[GIS] Show/filter features based on field value in Leaflet

leaflet

I have geoJSON file with an ID Field.

I would like to add an input box with where a user can enter a specific ID.

Based on this input only features with this ID would be displayed.

Can anyone point me in the right direction as to how I may achieve this.

Best Answer

You have to combine different stuffs. Here is a way to go:

1) The input search box:

Add an input field in your HTML DOM and add an event listener or a function (addFeature(id)) to it. When the user will type/select some ID, you need to trigger an action. You may need an autocompletion widget, as this one. I'll assume you know how to make it. Otherwise, make some research! This is a pure HTML/JS question, so have also a look at stackoverflow.com.

2) Filter the geojson:

Then, when your action is triggered, you may display only the feautres with a certain id using the pointToLayer method, with something like:

var addFeature = function (id) {
  var geojsonLayer = L.geoJson(yourGeojsonData, {
    pointToLayer: function(feature, latlng) {
        if (feature.ID == id) {
        return markerLayer = L.marker(latlng, {
          icon: // your icon styling function
        });
      }
    }
  }
  map.addLayer(geojsonLayer);
 }

I don't have your code and I don't know how you load your geojson, so you'll surely have to modify this function! In addition, you'll probably have to remove old layers when performing a new search (using map.removeLayer()).

The relevant doc is here: http://leafletjs.com/reference-1.2.0.html#geojson