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:

Some things I learned by fiddling around with Leaflet and Leaflet Geoman:

Add custom polygon buttons

Add a button to the draw toolbar that draws green polygons:

map.pm.Toolbar.copyDrawControl('Polygon', {
name: 'DrawEntry',
  block: 'draw',
  title: 'Draw Entry Polygon',
});
map.pm.Draw.DrawEntry.setPathOptions({ color: 'green' });

The icon is still a polygon icon. To change this I need a svg for a new icon.

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:

JSON.stringify(L.PM.Utils.findLayers(map)[0].toGeoJSON())

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:

screenshot

The two polygon icons are the same, but the first one draws entry colored polygons and the second one exit colored ones.