Leaflet 1.3.1(Leaflet.Draw)如何监听L.Polygon顶点点击事件?
Got it, let's break down how to listen for clicks on the vertices of your editable polygon created with Leaflet.Draw in Leaflet 1.3.1. Since you've already enabled vertex editing without using the control toolbar, here's the approach:
1. Access Edit Handlers & Bind Click Events
When your polygon is in edit mode, Leaflet.Draw creates small marker "handles" for each vertex. We need to target these handles and bind click events to them.
First, ensure your polygon is in edit mode (if it isn't already):
// Replace `polygon` with your actual L.Polygon instance polygon.enableEdit();
Next, loop through existing vertex handles and attach click listeners. We'll wrap this in a function to avoid duplicate bindings later:
function setupVertexClickListeners(polygon) { // Clean up existing listeners to prevent duplicate triggers polygon.editing._handlers.forEach(handler => { if (handler._marker) handler._marker.off('click'); }); // Bind click events only to vertex handles (skip add-point handles) polygon.editing._handlers.forEach(handler => { if (handler instanceof L.Draw.PolylineVertex) { handler._marker.on('click', e => { const clickedLatLng = e.target.getLatLng(); console.log(`Vertex clicked at: ${clickedLatLng.lat}, ${clickedLatLng.lng}`); // Add your custom logic here — e.g., show a popup, update backend data, or adjust styling }); } }); } // Initialize listeners right after enabling edit mode setupVertexClickListeners(polygon);
2. Handle Newly Added Vertices
If users can add new vertices while editing, you'll want to bind listeners to those as they're created. Use the draw:vertex:created event to catch these new vertices:
polygon.on('draw:vertex:created', e => { e.vertex._marker.on('click', clickEvent => { const newVertexLatLng = clickEvent.target.getLatLng(); console.log(`New vertex clicked at: ${newVertexLatLng.lat}, ${newVertexLatLng.lng}`); // Reuse your custom logic here or add specific behavior for new vertices }); });
3. Re-bind Listeners When Edit Mode is Re-enabled
If you ever disable and re-enable edit mode, the old vertex handles are destroyed and new ones are generated. Listen for the edit:enabled event to re-setup your click listeners automatically:
polygon.on('edit:enabled', () => { setupVertexClickListeners(polygon); });
Quick Troubleshooting Tip
Depending on your exact Leaflet.Draw version, the handler class name might differ. If L.Draw.PolylineVertex doesn't work, try checking for L.Edit.Vertex instead. You can inspect the handler object in your browser's dev tools to confirm the correct type.
内容的提问来源于stack exchange,提问作者Es Noguera

