Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet.js: is it possible to filter geoJSON features by property?

Tags:

filter

leaflet

I'm looking around and I see a lot of information about how to show/hide layers. That's cool, but since I can add arbitrary properties to GeoJSON features, I kind of expect to be able to filter them accordingly.

For instance, if I have features 1, 2 & 3 with these properties:

  1. small | red | sweet
  2. large | green | sour
  3. small | red | hot

How would I filter them by size? Or by color or flavor?

like image 359
doub1ejack Avatar asked Feb 23 '14 21:02

doub1ejack


People also ask

How do you plot GeoJSON in leaflet?

GeoJSON objects are added to the map through a GeoJSON layer. To create it and add it to a map, we can use the following code: L. geoJSON(geojsonFeature).

How do you filter GeoJSON in Python?

Filtering GeoJSON To use this function you need to have a list of the items you want to filter to. Once you have that, load your geojson file using the read_geojson function shown above. Set you output variable name and then call the filter_geojson function. Pass your geojson object and filter list.

How do you add a polygon to a leaflet?

Create a polygon using the L. Pass the locations/points as variable to draw the polygon, and an option to specify the color of the polygon. var polygon = L. polygon(latlngs, {color: 'red'}); Add the polygon to the map using the addTo() method of the Polygon class.

What is GeoJSON layer?

The GeoJsonLayer renders GeoJSON formatted data as polygons, lines and points (circles, icons and/or texts). GeoJsonLayer is a CompositeLayer. See the sub layers that it renders.


2 Answers

Please, see Using GeoJSON with Leaflet - Leaflet - a JavaScript library for interactive maps.

Yes, you can, just add a filter function like:

L.geoJson(someFeatures, {
    filter: function(feature, layer) {
        return feature.properties.show_on_map;
    }
}).addTo(map);

Or if you want dynamic updating, there's a great answer in this other SO question: Leaflet: Update GeoJson filter?

like image 106
Mike Lanzetta Avatar answered Oct 01 '22 09:10

Mike Lanzetta


I have added the plugin for filtering markers by tags at Leaflet.tagFilterButton.

If you add tags option to your markers you can filter them by your tags/categories. For example:

L.geoJson(jsonObject, {
    pointToLayer: function(feature, latlng) {
        L.marker(latlng, {
            tags: ['small', 'red', 'sweet']
        });
    }
}).addTo( map );

L.control.tagFilterButton({
    data: ['small', 'red', 'sweet']
}).addTo( map );
like image 40
Mehmet Aydemir Avatar answered Oct 01 '22 09:10

Mehmet Aydemir