Draw and Save a Polygon on a map
Drawing a Polygon and Saving it to GeoJSON is the next item on my exploration list.
First I tried a few Leaflet drawing plugins:
Leaflet Freedraw is not exactly what I need.
Leaflet Draw looked good, but no commits in years is not encouraging to start a new project using it.
Leaflet Editable is too complicated to use.
Leaflet Geoman is exactly what I want. The free version should be enough.
Some things I learned by fiddling around with Leaflet and Leaflet Geoman:
Save a drawn polygon to GeoJSON
I want to save this later into a database and may need a bit more meta information, i.e. color of the polygon. But this here is enough for today:
Load a polygon to the map
Add two exported polygons to the map, one as entry (green) and one as exit (violet).
var example = [ // entry {"type":"Feature","properties":{"type": "entry"},"geometry":{"type":"Polygon","coordinates":[[[9.003386,48.683486],[9.003185,48.68335],[9.003226,48.683275],[9.003769,48.683492],[9.003679,48.68359],[9.003386,48.683486]]]}}, // exit {"type":"Feature","properties":{"type": "exit"},"geometry":{"type":"Polygon","coordinates":[[[9.002798,48.683225],[9.002868,48.683157],[9.002577,48.683058],[9.002519,48.683127],[9.002798,48.683225]]]}} ] L.geoJSON(example, { style: function(feature) { if (feature.properties){ switch (feature.properties.type) { case 'entry': return {color: "green"}; case 'exit': return {color: "violet"}; }}}}).addTo(map);
The style function changes the color based on the "type" property in the GeoJSON. If the "type" is empty or not "entry" or "exit" the color is the default which is "blue".
Full Example
I used stadiamaps to have a higher zoom level (level 20) than the default openstreetmap map.
Only a screenshot for now:
The two polygon icons are the same, but the first one draws entry colored polygons and the second one exit colored ones.