1

Is it possible to export all points within a polygon drawn using Leaflet?

(http://leaflet.github.io/Leaflet.draw/).

  • 3
    Yes it is, but the implementation depends on what you mean by export. Also, do you just want to 'export' a polygon's shape or specifically all of its vertices? – BritishSteel Feb 6 '15 at 12:34
  • How can we do the same thing in React-leaflet. – MJB Nov 3 '18 at 12:52
5

It is simpler than that.

map.on('draw:created', function (e) {
    var type = e.layerType,
        layer = e.layer;

    if (type === 'polygon') {
        // here you got the polygon points
        var points = layer._latlngs;

        // here you can get it in geojson format
        var geojson = layer.toGeoJSON();
   }
   // here you add it to a layer to display it in the map
   drawnItems.addLayer(layer);
});
3

Although 'export' is very ambiguous, here's a way to console log the drawn polygon as 'geojson' string. Working from this example, replace the map.on('draw:created') callback with the following:

map.on('draw:created', function (e) {
    var type = e.layerType,
        layer = e.layer;

    if (type === 'polygon') {
        // structure the geojson object
        var geojson = {};
        geojson['type'] = 'Feature';
        geojson['geometry'] = {};
        geojson['geometry']['type'] = "Polygon";

        // export the coordinates from the layer
        coordinates = [];
        latlngs = layer.getLatLngs();
        for (var i = 0; i < latlngs.length; i++) {
            coordinates.push([latlngs[i].lng, latlngs[i].lat])
        }

        // push the coordinates to the json geometry
        geojson['geometry']['coordinates'] = [coordinates];

        // Finally, show the poly as a geojson object in the console
        console.log(JSON.stringify(geojson));

    }

    drawnItems.addLayer(layer);
});

From there, depending on what you mean by export, the solution could be as simple as opening your browser console (F12) to copy and save the json string as a geojson file, or as complex as posting the result to a server, and returning the file for download

  • Did OP find a solution to original question? Or can @toms elaborate on selecting markers in drawnItems with the polygon geojson. The solution [provided only returns a geojson of the polygon? – wtgeographer Mar 3 '17 at 19:15

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.