0.1.0 • Published 2 years ago

leaflet-geoman-tiny v0.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Opt-In

If you want to use Leaflet-Geoman as opt-in, call the following function right after importing:

L.PM.setOptIn(true);

And to disable it:

L.PM.setOptIn(false);

If you have enabled opt-in before you init the map, you need to specify pmIgnore: false in the map options:

const map = L.map('map', { pmIgnore: false });

All layers will be ignored by Leaflet-Geoman, unless you specify pmIgnore: false on a layer:

L.marker([51.50915, -0.096112], { pmIgnore: false }).addTo(map);

Newly drawn layers will be ignored as well.

To prevent this you can add the following event handler:

map.on('pm:create', (e) => {
  e.layer.setStyle({ pmIgnore: false });
  L.PM.reInitLayer(e.layer);
});

Leaflet-Geoman Toolbar

Draw Mode

Use Draw Mode on a map like this:

// enable polygon Draw Mode
map.pm.enableDraw('Polygon', {
  snappable: true,
  snapDistance: 20,
});

// disable Draw Mode
map.pm.disableDraw();

Currently available shapes are Marker, CircleMarker, Circle, Line, Rectangle, Polygon and Cut.

The following methods are available on map.pm:

MethodReturnsDescription
enableDraw(shape,options)-Enable Draw Mode with the passed shape. The options are optional.
disableDraw()-Disable Draw Mode.
Draw.getShapes()ArrayArray of available shapes.
Draw.getActiveShape()StringReturns the active shape.
globalDrawModeEnabled()BooleanReturns true if global Draw Mode is enabled. false when disabled.
setPathOptions(options, optionsModifier)-Customize the style of the drawn layer. Only for L.Path layers. Shapes can be excluded with a ignoreShapes array or merged with the current style with merge: true in optionsModifier Details.
setGlobalOptions(options)-Set globalOptions and apply them.
applyGlobalOptions()-Apply the current globalOptions to all existing layers.
getGlobalOptions()ObjectReturns the globalOptions.
getGeomanLayers(Boolean)ArrayReturns all Leaflet-Geoman layers on the map as array. Pass true to get a L.FeatureGroup.
getGeomanDrawLayers(Boolean)ArrayReturns all drawn Leaflet-Geoman layers on the map as array. Pass true to get a L.FeatureGroup.

See the available options in the table below.

OptionDefaultDescription
snappabletrueEnable snapping to other layers vertices for precision drawing. Can be disabled by holding the ALT key.
snapDistance20The distance to another vertex when a snap should happen.
snapMiddlefalseAllow snapping in the middle of two vertices (middleMarker).
snapSegmenttrueAllow snapping between two vertices.
requireSnapToFinishfalseRequire the last point of a shape to be snapped.
tooltipstrueShow helpful tooltips for your user.
allowSelfIntersectiontrueAllow self intersections.
templineStyle{ color: 'red' },Leaflet path options for the lines between drawn vertices/markers.
hintlineStyle{ color: 'red', dashArray: [5, 5] }Leaflet path options for the helper line between last drawn vertex and the cursor.
pathOptionsnullLeaflet path options for the drawn layer (Only for L.Path layers).
markerStyle{ draggable: true }Leaflet marker options (only for drawing markers).
cursorMarkertrueShow a marker at the cursor.
finishOnnullLeaflet layer event to finish the drawn shape, like 'dblclick'. Here's a list. snap is also an option for Line, Polygon and Rectangle.
hideMiddleMarkersfalseHide the middle Markers in Edit Mode from Polyline and Polygon.
minRadiusCirclenullSet the min radius of a Circle.
maxRadiusCirclenullSet the max radius of a Circle.
minRadiusCircleMarkernullSet the min radius of a CircleMarker when editable is active.
maxRadiusCircleMarkernullSet the max radius of a CircleMarker when editable is active.
editablefalseMakes a CircleMarker editable like a Circle.
markerEditabletrueMarkers and CircleMarkers are editable during the draw-session (you can drag them around immediately after drawing them).
continueDrawingfalse / trueDraw Mode stays enabled after finishing a layer to immediately draw the next layer. Defaults to true for Markers and CircleMarkers and false for all other layers.
rectangleAngle0Rectangle can drawn with a rotation angle 0-360 degrees
layersToCut[]Cut-Mode: Only the passed layers can be cut. Cutted layers are removed from the Array until no layers are left anymore and cutting is working on all layers again.

This options can only set over map.pm.setGlobalOptions({}):

OptionDefaultDescription
layerGroupmapAdd the created layers to a layergroup instead to the map.

You can listen to map events to hook into the drawing procedure like this:

map.on('pm:drawstart', (e) => {
  console.log(e);
});

Here's a list of map events you can listen to:

EventParamsDescriptionOutput
pm:globaldrawmodetoggledeFired when Drawing Mode is toggled.enabled, shape, map
pm:drawstarteCalled when Draw Mode is enabled. Payload includes the shape type and working layer.shape, workingLayer
pm:drawendeCalled when Draw Mode is disabled. Payload includes the shape type.shape
pm:createeCalled when a shape is drawn/finished. Payload includes shape type and the drawn layer.shape, layer

There are also several events for layers during draw. Register an event like this:

// listen to vertexes being added to currently drawn layer (called workingLayer)
map.on('pm:drawstart', ({ workingLayer }) => {
  workingLayer.on('pm:vertexadded', (e) => {
    console.log(e);
  });
});

Here's a list of layer events you can listen to:

EventParamsDescriptionOutput
pm:vertexaddedeCalled when a new vertex is added. Payload includes the new vertex, it's marker, index, working layer and shape type.shape, workingLayer, marker, latlng
pm:snapdrageFired during a marker move/drag. Payload includes info about involved layers and snapping calculation.shape, distance, layer = workingLayer, marker, layerInteractedWith, segment, snapLatLng
pm:snapeFired when a vertex is snapped. Payload is the same as in snapdrag.shape, distance, layer = workingLayer, marker, layerInteractedWith, segment, snapLatLng
pm:unsnapeFired when a vertex is unsnapped. Payload is the same as in snapdrag.shape, distance, layer = workingLayer, marker, layerInteractedWith, segment, snapLatLng
pm:centerplacedeCalled when the center of a circle is placed/moved.shape, workingLayer, latlng

For making the snapping to other layers selective, you can add the "snapIgnore" option to your layers to disable the snapping to them during drawing.

//This layer will be ignored by the snapping engine during drawing
L.geoJSON(data, {
  snapIgnore: true,
});

Edit Mode

You can enable Edit Mode for all layers on a map like this:

// enable global Edit Mode
map.pm.enableGlobalEditMode(options);

The following methods are available on map.pm:

MethodReturnsDescription
enableGlobalEditMode(options)-Enables global Edit Mode.
disableGlobalEditMode()-Disables global Edit Mode.
toggleGlobalEditMode(options)-Toggles global Edit Mode.
globalEditModeEnabled()BooleanReturns true if global Edit Mode is enabled. false when disabled.

Enable Edit Mode only for one layer:

// enable Edit Mode
layer.pm.enable({
  allowSelfIntersection: false,
});

The following methods are available for layers under layer.pm:

MethodReturnsDescription
enable(options)-Enables Edit Mode. The passed options are preserved, even when the mode is enabled via the Toolbar. options is optional.
disable()-Disables Edit Mode.
toggleEdit(options)-Toggles Edit Mode. Passed options are preserved. options is optional.
enabled()BooleanReturns true if Edit Mode is enabled. false when disabled.
hasSelfIntersection()BooleanReturns true if Line or Polygon has a self intersection.
remove()-Removes the layer with the same checks as GlobalRemovalMode.
getShape()StringReturns the shape of the layer.
setOptions(options)-Set the options on the layer.
getOptions()ObjectReturns the options of the layer.

See the available options in the table below.

OptionDefaultDescription
snappabletrueEnable snapping to other layers vertices for precision drawing. Can be disabled by holding the ALT key.
snapDistance20The distance to another vertex when a snap should happen.
allowSelfIntersectiontrueAllow/Disallow self-intersections on Polygons and Polylines.
allowSelfIntersectionEditfalseAllow/Disallow to change vertices they are connected to a intersecting line. Only working if allowSelfIntersection is true and the layer is already self-intersecting while enabling Edit Mode.
preventMarkerRemovalfalseDisable the removal of markers/vertexes via right click.
removeLayerBelowMinVertexCounttrueIf true, vertex removal that cause a layer to fall below their minimum required vertices will remove the entire layer. If false, these vertices can't be removed. Minimum vertices are 2 for Lines and 3 for Polygons.
syncLayersOnDragfalseDefines which layers should dragged with this layer together. true syncs all layers in the same LayerGroup(s) or you pass an Array of layers to sync.
allowEditingtrueEdit-Mode for the layer can disabled (pm.enable()).
allowRemovaltrueRemoving can be disabled for the layer.
allowCuttingtrueLayer can be prevented from cutting.
allowRotationtrueLayer can be prevented from rotation.
draggabletrueDragging can be disabled for the layer.
addVertexOnclickLeaflet layer event to add a vertex to a Line or Polygon, like 'dblclick'. Here's a list.
addVertexValidationundefinedA function for validation if a vertex (of a Line / Polygon) is allowed to add. It passes a object with [layer, marker, event}. For example to check if the layer has a certain property or if the Ctrl key is pressed.
removeVertexOncontextmenuLeaflet layer event to remove a vertex from a Line or Polygon, like 'dblclick'. Here's a list.
removeVertexValidationundefinedA function for validation if a vertex (of a Line / Polygon) is allowed to remove. It passes a object with [layer, marker, event}. For example to check if the layer has a certain property or if the Ctrl key is pressed.
moveVertexValidationundefinedA function for validation if a vertex / helper-marker is allowed to move / drag. It passes a object with [layer, marker, event}. For example to check if the layer has a certain property or if the Ctrl key is pressed.
limitMarkersToCount-1Shows only n markers closest to the cursor. Use -1 for no limit.
limitMarkersToZoom-1Shows markers when under the given zoom level. ⭐
limitMarkersToViewportfalseShows only markers in the viewport. ⭐
limitMarkersToClickfalseShows markers only after the layer was clicked. ⭐
pinningfalsePin shared vertices/markers together during edit Details. ⭐
centerScalingtrueScale origin is the center, else it is the opposite corner. If false Alt-Key can be used. Scale Mode. ⭐
uniformScalingtrueWidth and height are scaled with the same ratio. If false Shift-Key can be used. Scale Mode. ⭐

You can listen to events related to editing on events like this:

// listen to when a layer is changed in Edit Mode
layer.on('pm:edit', (e) => {
  console.log(e);
});

The following events are available on a layer instance:

EventParamsDescriptionOutput
pm:editeFired when a layer is edited.layer, shape
pm:updateeFired when Edit Mode is disabled and a layer is edited and its coordinates have changed.layer, shape
pm:enableeFired when Edit Mode on a layer is enabled.layer, shape
pm:disableeFired when Edit Mode on a layer is disabled.layer, shape
pm:vertexaddedeFired when a vertex is added.layer, indexPath, latlng, marker, shape
pm:vertexremovedeFired when a vertex is removed.layer, indexPath, marker, shape
pm:vertexclickeFired when a vertex is clicked.layer, indexPath, markerEvent, shape
pm:markerdragstarteFired when dragging of a marker which corresponds to a vertex starts.layer, indexPath, markerEvent, shape
pm:markerdrageFired when dragging a vertex-marker.layer, indexPath, markerEvent, shape
pm:markerdragendeFired when dragging of a vertex-marker ends.layer, indexPath, markerEvent, shape, intersectionReset
pm:layerreseteFired when coords of a layer are reset. E.g. by self-intersection.layer, indexPath, markerEvent, shape
pm:snapdrageFired during a marker move/drag. Payload includes info about involved layers and snapping calculation.shape, distance, layer = workingLayer, marker, layerInteractedWith, segment, snapLatLng
pm:snapeFired when a vertex-marker is snapped to another vertex. Also fired on the marker itself.shape, distance, layer = workingLayer, marker, layerInteractedWith, segment, snapLatLng
pm:unsnapeFired when a vertex-marker is unsnapped from a vertex. Also fired on the marker itself.shape, distance, layer = workingLayer, marker, layerInteractedWith, segment, snapLatLng
pm:intersecteWhen allowSelfIntersection: false, this event is fired as soon as a self-intersection is detected.layer, intersection, shape
pm:centerplacedeFired when the center of a circle is moved.layer, latlng, shape

The following events are available on a map instance:

EventParamsDescriptionOutput
pm:globaleditmodetoggledeFired when Edit Mode is toggled.enabled, map

You can also listen to specific Edit Mode events on the map instance like this:

map.on('pm:globaleditmodetoggled', (e) => {
  console.log(e);
});

Drag Mode

You can enable Drag Mode for all layers on a map like this:

// enable Drag Mode like this:
map.pm.enableGlobalDragMode();

Or you enable dragging for a specific layer:

layer.pm.enableLayerDrag();

The following methods are available on layer.pm:

MethodReturnsDescription
enableLayerDrag()-Enables dragging for the layer.
disableLayerDrag()-Disables dragging for the layer.
layerDragEnabled()BooleanReturns if Drag Mode is enabled for the layer.
dragging()BooleanReturns if the layer is currently dragging.

The following methods are available on map.pm:

MethodReturnsDescription
enableGlobalDragMode()-Enables global Drag Mode.
disableGlobalDragMode()-Disables global Drag Mode.
toggleGlobalDragMode()-Toggles global Drag Mode.
globalDragModeEnabled()BooleanReturns true if global Drag Mode is enabled. false when disabled.

The following events are available on a layer instance:

EventParamsDescriptionOutput
pm:dragstarteFired when a layer starts being dragged.layer, shape
pm:drageFired when a layer is dragged.layer, containerPoint,latlng, layerPoint,originalEvent, shape
pm:dragendeFired when a layer stops being dragged.layer, shape

The following events are available on a map instance:

EventParamsDescriptionOutput
pm:globaldragmodetoggledeFired when Drag Mode is toggled.enabled, map

You can also listen to specific Drag Mode events on the map instance like this:

map.on('pm:globaldragmodetoggled', (e) => {
  console.log(e);
});

Removal Mode

You can enable Removal Mode for all layers on a map like this:

// enable removal mode like this:
map.pm.enableGlobalRemovalMode();

The following methods are available on map.pm:

MethodReturnsDescription
enableGlobalRemovalMode()-Enables global removal mode.
disableGlobalRemovalMode()-Disables global removal mode.
toggleGlobalRemovalMode()-Toggles global removal mode.
globalRemovalModeEnabled()BooleanReturns true if global removal mode is enabled. false when disabled.

The following events are available on a layer instance:

EventParamsDescriptionOutput
pm:removeeFired when a layer is removed via Removal Modelayer, shape

The following events are available on a map instance:

EventParamsDescriptionOutput
pm:globalremovalmodetoggledeFired when Removal Mode is toggledenabled, map
pm:removeeFired when a layer is removed via Removal Modelayer, shape
layerremoveeStandard Leaflet event. Fired when any layer is removed.layer

You can also listen to specific removal mode events on the map instance like this:

map.on('pm:globalremovalmodetoggled', (e) => {
  console.log(e);
});

Cut Mode

cut polygon

Enables drawing for the shape "Cut" to draw a polygon that gets subtracted from all underlying polygons. This way you can create holes, cut polygons or polylines in half or remove parts of it.

Important: the cutted layer will be replaced, not updated. Listen to the pm:cut event to update your layer references in your code. The pm:cut event will provide you with the original layer and returns the resulting layer(s) that is/are added to the map as a Polygon / MultiPolygon or Polyline / MultiPolyline.

// enable cutting mode
map.pm.enableGlobalCutMode({
  allowSelfIntersection: false,
});

Available options are the same as in Draw Mode. If the option layersToCut: [layer1, layer2] is passed, only this certain layers will be cutted.

The following methods are available on map.pm:

MethodReturnsDescription
enableGlobalCutMode(options)-Enable Cut Mode.
disableGlobalCutMode()-Disable Cut Mode.
toggleGlobalCutMode(options)-Toggle Cut Mode.
globalCutModeEnabled()BooleanReturns true if global cut mode is enabled. false when disabled.

The following events are available on a layer instance:

EventParamsDescriptionOutput
pm:cuteFired when the layer being cut.shape, layer, originalLayer
pm:editeFired when a layer is edited / cut.layer, shape

The following events are available on a map instance:

EventParamsDescriptionOutput
pm:globalcutmodetoggledeFired when Cut Mode is toggled.enabled, map
pm:cuteFired when any layer is being cut.shape, layer, originalLayer

Rotation Mode

Rotation Feature

The rotation is clockwise. It starts in the North with 0° and goes over East (90°) and South (180°) to West (270°). The rotation center is the center (layer.getCenter()) of a Polygon with the LatLngs of the layer.

You can enable Rotate Mode for all layers on a map like this:

map.pm.enableGlobalRotateMode();

The following methods are available on map.pm:

MethodReturnsDescription
enableGlobalRotateMode()-Enables global Rotate Mode.
disableGlobalRotateMode()-Disables global Rotate Mode.
toggleGlobalRotateMode()-Toggles global Rotate Mode.
globalRotateModeEnabled()BooleanReturns true if global Rotate Mode is enabled. false when disabled.

The following methods are available for layers under layer.pm:

MethodReturnsDescription
enableRotate()-Enables Rotate Mode on the layer.
disableRotate()-Disables Rotate Mode on the layer.
rotateEnabled()BooleanReturns if Rotate Mode is enabled for the layer.
rotateLayer(degrees)-Rotates the layer by x degrees.
rotateLayerToAngle(degrees)-Rotates the layer to x degrees.
getAngle()DegreesReturns the angle of the layer in degrees.

The following events are available on a layer instance:

EventParamsDescriptionOutput
pm:rotateenableeFired when rotation is enabled for a layer.layer, helpLayer
pm:rotatedisableeFired when rotation is disabled for a layer.layer
pm:rotatestarteFired when rotation starts on a layer.layer, helpLayer, startAngle, originLatLngs
pm:rotateeFired when a layer is rotated.layer, helpLayer, startAngle, angle, angleDiff, oldLatLngs, newLatLngs
pm:rotateendeFired when rotation ends on a layer.layer, helpLayer, startAngle, angle, originLatLngs, newLatLngs

The following events are available on a map instance:

EventParamsDescriptionOutput
pm:globalrotatemodetoggledeFired when Rotate Mode is toggled.enabled, map
pm:rotateenableeFired when rotation is enabled for a layer.layer, helpLayer
pm:rotatedisableeFired when rotation is disabled for a layer.layer
pm:rotatestarteFired when rotation starts on a layer.layer, helpLayer, startAngle, originLatLngs
pm:rotateeFired when a layer is rotated.layer, helpLayer, startAngle, angle, angleDiff, oldLatLngs, newLatLngs
pm:rotateendeFired when rotation ends on a layer.layer, helpLayer, startAngle, angle, originLatLngs, newLatLngs

Split Mode ⭐

Split Mode Demo

Enable drawing for the shape "Split" to draw a line that splits all underlying Polygons and Polylines.

Important: the splitted layer will be replaced, not updated. Listen to the pm:split event to update your layer references in your code. The pm:split event will provide you with the original layer and returns the resulting layer(s) that is/are added to the map as a Polygon / MultiPolygon or Polyline / MultiPolyline.

// enable cutting mode
map.pm.enableGlobalSplitMode({
  allowSelfIntersection: false,
});

Available options are the same as in Draw Mode and in table below:

OptionDefaultDescription
splitOnlyMarkedLayersfalseIf it is set to false layers can be excluded with the option splitMark: false. Set it to true to enable splitting only for the layers with the option splitMark: true.

The following methods are available on map.pm:

MethodReturnsDescription
enableGlobalSplitMode(options)-Enable Split Mode.
disableGlobalSplitMode()-Disable Split Mode.
toggleGlobalSplitMode(options)-Toggle Split Mode.
globalSplitModeEnabled()BooleanReturns true if global Split Mode is enabled. false when disabled.

The following events are available on a layer instance:

EventParamsDescriptionOutput
pm:spliteFired when the layer being split. Returns a LayerGroup containing all resulting layers in layers.shape, splitLayer, layers, originalLayer

The following events are available on a map instance:

EventParamsDescriptionOutput
pm:globalsplitmodetoggledeFired when Split Mode is toggled.enabled, map
pm:spliteFired when any layer is being split.shape, splitLayer, layers, originalLayer

Scale Mode ⭐

You can enable Scale Mode for all layers on a map like this:

map.pm.enableGlobalScaleMode();

With the option centerScaling the scale origin cen be the center of the layer or the opposite corner of the dragged marker. If false Alt-Key can be used. The option uniformScaling the scales the width and the height with the same ratio. If false Shift-Key can be used.

The following methods are available on map.pm:

MethodReturnsDescription
enableGlobalScaleMode()-Enables global Scale Mode.
disableGlobalScaleMode()-Disables global Scale Mode.
toggleGlobalScaleMode()-Toggles global Scale Mode.
globalScaleModeEnabled()BooleanReturns true if global Scale Mode is enabled. false when disabled.

The following methods are available for layers under layer.pm:

MethodReturnsDescription
enableScale()-Enables Scale Mode on the layer.
disableScale()-Disables Scale Mode on the layer.
scaleEnabled()BooleanReturns if Scale Mode is enabled for the layer.
scaleLayer(percent)-Scale the layer by x percent. Also an Object with {w: width, h: height} can be passed. Scale up > 0 , scale down < 0.

The following events are available on a layer instance:

EventParamsDescriptionOutput
pm:scaleenableeFired when scale is enabled for a layer.layer, helpLayer
pm:scaledisableeFired when scale is disabled for a layer.layer
pm:scalestarteFired when scale starts on a layer.layer, helpLayer, originLatLngs, originLatLngs
pm:scaleeFired when a layer is scaled.layer, helpLayer, oldLatLngs, newLatLngs
pm:scaleendeFired when scale ends on a layer.layer, helpLayer, originLatLngs, newLatLngs

The following events are available on a map instance:

EventParamsDescriptionOutput
pm:globalscalemodetoggledeFired when Scale Mode is toggled.enabled, map
pm:scaleenableeFired when scale is enabled for a layer.layer, helpLayer
pm:scaledisableeFired when scale is disabled for a layer.layer
pm:scalestarteFired when scale starts on a layer.layer, helpLayer, originLatLngs, originLatLngs
pm:scaleeFired when a layer is scaled.layer, helpLayer, oldLatLngs, newLatLngs
pm:scaleendeFired when scale ends on a layer.layer, helpLayer, originLatLngs, newLatLngs

Options

You have many options available when drawing and editing your layers (described above).
You can set the options per layer as described above, or you can set them globally for all layers. This is especially useful when you use the toolbar and can't change the options programmatically.

Examples:

layer.pm.enable({ pinning: true, snappable: false });
map.pm.setGlobalOptions({ pinning: true, snappable: false });

The following options are additionally to the Draw and Edit Mode options.

OptionDefaultDescription
snappingOrderArrayPrioritize the order of snapping. Default: ['Marker','CircleMarker','Circle','Line','Polygon','Rectangle'].
layerGroupmapadd the created layers to a layergroup instead to the map.
panesObjectDefines in which panes the layers and helper vertices are created. Default: { vertexPane: 'markerPane', layerPane: 'overlayPane', markerPane: 'markerPane' }.

Some details about a few more powerful options:

Snapping

Snap the dragged marker/vertex to other layers for precision drawing.
Snapping can be disabled for layers with the layer option snapIgnore: true. With snapIgnore: false it will be always snappable, also if pmIgnore is set. Can also be disabled by holding the ALT key.

Snapping Options

Pinning ⭐

When dragging a vertex/marker, you can pin all other Markers/Vertices that have the same latlng to the dragged marker. Exclusive for Leaflet-Geoman Pro ⭐

Pinning Option

Measurement ⭐

Measurement Demo

Calculates the measurement of a layer while drawing and editing. Exclusive for Leaflet-Geoman Pro ⭐

map.pm.setGlobalOptions({ measurements: { measurement: true, displayFormat: 'metric', ... } })

See the available options in the table below.

OptionDefaultDescription
measurementtrueEnable measurement calculation.
showTooltiptrueShows the tooltip during draw and edit.
showTooltipOnHovertrueShows the tooltip when hovering a finished layer.
displayFormatmetricDisplayed format in the tooltip metric or imperial.
totalLengthtrueShows the total length in the tooltip Line.
segmentLengthtrueShows the segment length in the tooltip Line, Polygon.
areatrueShows the area in the tooltip Polygon, Rectangle, Circle, CircleMarker.
radiustrueShows the radius in the tooltip Circle, CircleMarker.
perimetertrueShows the perimeter in the tooltip Polygon, Rectangle, Circle, CircleMarker.