Skip to content

toGeoJSON #712

@jfgirard

Description

@jfgirard

Hi,
I'm working with L.GeoJSON and the editing tools. I didn't find a built-in way to extract the GeoJSON from a layer when it's time to save back to server.

Here is what I did. The target variable is from the click event (e.target):

toGeoJSON: function(target) {
    if (target instanceof L.Marker) {
        //Point
        return {
            coordinates: this.latLngToCoords(target.getLatLng()),
            type: 'Point'
        }
    } else if (target instanceof L.MultiPolygon || target instanceof L.MultiPolyline) {
        //MultiPolygon and MultiLineString
        var multi = [];
        var layers = target._layers;
        for (var stamp in layers) {
            multi.push(this.toGeoJSON(layers[stamp]).coordinates);
        }
        return {
            coordinates: multi,
            type: (target instanceof L.MultiPolygon) ? 'MultiPolygon': 'MultiLineString'
        };
    } else if (target instanceof L.Polygon) {
        //Polygon
        var coords = this.latLngsToCoords(target.getLatLngs());
        return {
            coordinates: [coords],
            type: 'Polygon'
        };
    } else if (target instanceof L.Polyline) {
        //Linestring
        var coords = this.latLngsToCoords(target.getLatLngs());
        return {
            coordinates: coords,
            type: 'LineString'
        };
    } else if (target instanceof L.FeatureGroup) {
        //Multi point and GeometryCollection
        var multi = [];
        var layers = target._layers;
        var points = true;
        for (var stamp in layers) {
            var json = this.toGeoJSON(layers[stamp]);
            multi.push(json);
            if (json.type !== 'Point') {
                points = false;
            }
        }
        if (points) {
            var coords = multi.map(function(geo){
                return geo.coordinates;
            });
            return {
                coordinates: coords,
                type: 'MultiPoint'
            };
        } else {
            return {
                geometries: multi,
                type: 'GeometryCollection'
            };
        }
    }
},

latLngToCoords: function(latlng) {
    return [latlng.lng, latlng.lat];
},

latLngsToCoords: function(arrLatlng) {
    var coords = [];
    arrLatlng.forEach(function(latlng) {
        coords.push(this.latLngToCoords(latlng));
    },
    this);
    return coords;
}

I don't know where to include such a function in the leaflet framework... But I think it would be very useful working with edit tools.

Jeff

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions