Reputation: 368
I am facing a problem when I am trying to draw a polyline using the Leaflet.Draw plugin.
First, I click on map to plot first point, and then second click to complete line.
However, after I clicked the line a second time, the line doesn't complete itself. It shows a extension to the line.
When I double-click it, the line completes, or else I need to manually click the finish button. I want to finish that line on second click on map.
This is my code for drawing a Polyline:
var drawControl = new L.Control.Draw({
position: 'topleft',
draw: {
polygon: {
allowIntersection: true,
showArea: true,
drawError: {
color: '#b00b00',
timeout: 1000
},
shapeOptions: {
color: '#0033ff'
}
},
circle: {
shapeOptions: {
color: '#0033ff'
}
},
polyline: {
shapeOptions: {
color: 'red'
},
},
rectangle: {
shapeOptions: {
color: '#0033ff'
}
},
marker: false,
polyline: true,
},
edit: {
featureGroup: drawnItems,
remove: true
}
});
Upvotes: 1
Views: 6005
Reputation: 219
You can trigger the second click automatically to complete the shape.
map.on('draw:drawvertex', e => {
const layerIds = Object.keys(e.layers._layers);
if (layerIds.length > 1) {
const secondVertex = e.layers._layers[layerIds[1]]._icon;
requestAnimationFrame(() => secondVertex.click());
}
});
Upvotes: 2
Reputation: 1982
You can override addVertex
function from L.Draw.Polyline
class, which resides in Leaflet.draw/src/draw/handler/Draw.Polyline.js, using prototype
in javascript, and add the following code at the end of it:
markersLength = this._markers.length;
if (markersLength == 2) {
this._fireCreatedEvent();
this.disable();
}
And, here is the full code:
L.Draw.Polyline.prototype.addVertex = function (latlng) {
var markersLength = this._markers.length;
// markersLength must be greater than or equal to 2 before intersections can occur
if (markersLength >= 2 && !this.options.allowIntersection && this._poly.newLatLngIntersects(latlng)) {
this._showErrorTooltip();
return;
}
else if (this._errorShown) {
this._hideErrorTooltip();
}
this._markers.push(this._createMarker(latlng));
this._poly.addLatLng(latlng);
if (this._poly.getLatLngs().length === 2) {
this._map.addLayer(this._poly);
}
this._vertexChanged(latlng, true);
markersLength = this._markers.length;
if (markersLength == 2) {
this._fireCreatedEvent();
this.disable();
}
};
Upvotes: 6
Reputation: 11116
Adding multiple vertices on polylines (e.g., not finishing polylines automatically on the second click) is a feature of Leaflet.Draw
.
You may be able to modify this behavior. I recommend that you look at the Leaflet.draw documentation, particularly the L.Draw.Polyline.completeShape() method.
Upvotes: 2