3

I find it quite practical to work with leaflet Polygon and it would be great to be able to build such objects directly from GeoJSON content. I did not find any Polygon constructor taking neither a GeoJSON object nor a GeoJSON string as input. Is there some method to build a leaflet polygon directly from a feature or an array of polygons from a featurecollection?

Something like:

geoJ = GeoJSON object returned/parsed from ajax call
pol = L.polygon( geoJ.features[0] )
bounds = pol.getBounds()
4
  • 2
    Is there a reason you can't just use L.geoJson? – nathansnider Dec 11 '15 at 15:58
  • I do not want to show the polygon on the map, just process it and use the leaflet class for that. – a1an Dec 14 '15 at 16:30
  • 1
    As nathansnider suggested, you could easily use L.geoJson(geoJ) to perform the conversion. It does not show anything on map as long as you do not explicitly ask Leaflet to do so (map.addLayer). Then you would iterate through each layer (corresponding to each polygon) with eachLayer() method. – ghybs Dec 15 '15 at 5:00
  • L.geoJson does indeed work and provides the getBounds method that I need. It also provides correct coordinates but they are for the entire FeatureGroup. When a collection is used it indeed provides getBounds on each feature, which wondered me a bit until I noticed that the actual layer (which provides no such method) is indeed set to an L.Polygon according to geojson content! Thanks – a1an Dec 17 '15 at 14:49
2

Besides converting a feature to a Polygon with a dedicated function (see this answer), L.geoJson(geoJ) can be used to get a collection of objects. In case the input geoJ contains polygons, the objects themselves will be set to be L.Polygons, hence the conversion is done automatically. Summing up in both cases:

geoJ = GeoJSON object returned/parsed from ajax call
pol = L.polygon( geoJ.features[0] )
bounds = pol.getBounds()

and

geoJ = GeoJSON object returned/parsed from ajax call
polCollection = L.polygon( geoJ )
polCollection.eachLayer( function(pol) {
    bounds = pol.getBounds()
})

give access to the(each) polygon bounds.

Thanks to @nathansnider and @ghybs for the useful comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.