How to chose one feature from multifeature GeoJSON

970 views
Skip to first unread message

Michael Johansson

unread,
Dec 14, 2016, 9:48:23 AM12/14/16
to Leaflet
Hi!

I have an external GeoJSON file with a couple of polygon features. You can see it here http://bl.ocks.org/d/41b25d26989d211bd86744dd4ffb82f2
I'm sorry if this has been asked before but I didn't find a good answer.

I want to add one polygon feature from that GeoJSON to my leaflet map, not all the features. How would I go about doing that?.

As of now this is how my script looks like. Not that much at the moment since I don't really know where to start. So any pointers in a direction would be appreciated.

<script>
   
var map = L.map('map').setView([43.64701, -79.39425], 15);

   
//Load Geojson from external, local file
    $
.getJSON("polygons.geojson",function(data){
   
// add GeoJSON layer to the map once the file is loaded
    geojsonLayer
= L.geoJson(data).addTo(map);
    map
.fitBounds(geojsonLayer.getBounds());
   
});

</script>


The end goal is to add one polygon at a time. Then extract coordinates from that polygon and then calling an API with those coordinates to get a image from that area. Then simply add that as a layer to leaflet.
I know how to do it all, except for the load only one polygon at a time from the GeoJSON.

//Michael


Matt Travis

unread,
Dec 15, 2016, 5:58:46 AM12/15/16
to Leaflet
Hi Michael

You could try using the filter function: http://leafletjs.com/reference-1.0.2.html#geojson-filter


Not sure if that works with mapbox though which is what your example is using.

Cheers

Matt

Michael Johansson

unread,
Dec 16, 2016, 1:20:52 PM12/16/16
to Leaflet
Thank you!
I did solve it with the filter function.
I don't know how I missed that method :)

And I am using leaflet, the link was just to an online service to show GeoJSON stuff.

The code for the map part looks like this now:

    var map = L.map('map')

       
.addLayer(OSMlayer)
       
.setView([42.444508, -76.499491], 12);
   
   
//Load the GeoJSON
   
var promise = $.getJSON("polygons.geojson");
    promise
.then(function(data) {
               
       
//A variable for all the polygons
       
var allpolygons = L.geoJson(data);
               
       
//A variable for only one polygon selected from the "ID" property in the GeoJSON
       
var firstpoly = L.geoJson(data, {
            filter
: function(feature, layer) {
               
return feature.properties.ID == 1;
           
}
       
});
       
// Add the first feature to the map
        firstpoly
.addTo(map)
});

Reply all
Reply to author
Forward
0 new messages