CloudMade/Leaflet — pull request #357 by chosak (2011-11-02 04:41:21+00:00)
Title: Create layer from GeoJSON object

GeoJSON support in Leaflet is great, but it has one limitation that I've tried to fix.

As the documentation describes, current supported usage is to first create a GeoJSON layer and then add some GeoJSON to it:

```js
var geojson = new L.GeoJSON();
var geojsonObj = {' ... my GeoJSON ...'},
geojsonObj2 = {' ... my other GeoJSON ...'};
geojson.addGeoJSON(geojsonObj1);
geojson.addGeoJSON(geojsonObj2);
```

Under the hood, this adds a group of layers to the ```geojson``` object, depending on what is defined in the provided GeoJSON. Unfortunately, there's no way to then keep a reference to what was added, for example if a user wanted to remove or modify them later. This is because the ```addGeoJSON``` method doesn't return a reference to the added layer(s).

There is a useful static function, ```geometryToLayer```, that converts a GeoJSON Geometry object to a Leaflet layer. This function is limited to only Geometry objects (Points, etc) or GeometryCollection objects, and does not support GeoJSON Features or FeatureCollections.

This pull request modifies GeoJSON.js to add a new function, ```geoJSONToLayer```. This function takes in any GeoJSON object (including Features and FeatureCollections) and returns the appropriate Leaflet overlay for that object. This allows users to do something like:

```js
var geojson = new L.GeoJSON();
var geojsonObj1 = {' ... my GeoJSON ...'},
geojsonObj2 = {' ... my other GeoJSON ...'},
geoLayer1 = L.GeoJSON.geoJSONToLayer(geojsonObj1),
geoLayer2 = L.GeoJSON.geoJSONToLayer(geojsonObj2);

geojson.addLayer(geoLayer1);
geojson.addLayer(geoLayer2);
geojson.removeLayer(geoLayer1);
```

While it would be simpler to modify the ```addGeoJSON``` function to just return the added layer, this would still assume that users would want to always add the layer right when creating it. The proposed change allows for layers to be created ahead of time and added only when needed.

The new ```geoJSONToLayer``` function takes an argument for a ```pointToLayer``` callback (like the existing ```geometryToLayer```), but it adds another argument for an ```onFeatureParse``` callback. This allows users to provide a callback to be invoked whenever a GeoJSON feature is parsed using this new static function. When GeoJSON is added using the current ```addGeoJSON``` function, existing callback functionality using

```js
geojson.on('featureparse', function(e) { ... });
```

is maintained.