DEV Community

Cover image for How to Edit Routes with Drag and Drop on a Leaflet Map
Casey Rivers for Geoapify Maps API

Posted on

How to Edit Routes with Drag and Drop on a Leaflet Map

In the previous tutorial, we built a drag-and-drop route editor with MapLibre GL. Now let's implement the same functionality with Leaflet.

The UX goals remain the same: drag markers to reposition, hover on route to add stops, click via points to remove. If you haven't read the MapLibre GL article, check it for the detailed UX principles and interaction patterns. This article focuses on the Leaflet-specific implementation differences.

APIs used:

What you will learn:

  • Key differences between Leaflet and MapLibre GL for route editing
  • Creating invisible hover detection layers in Leaflet
  • Using L.divIcon for custom floating markers
  • Managing application state with a clean architecture
  • Building a sidebar panel for waypoint management

Table of Contents

  1. Leaflet vs MapLibre GL: Key Differences
  2. Application State Management
  3. Creating the Hover Detection Layer
  4. The Floating Marker with L.divIcon
  5. Waypoint Markers with Tooltips
  6. Building the Sidebar Panel
  7. Explore the Demo
  8. Summary
  9. FAQ

Leaflet vs MapLibre GL: Key Differences

While the user experience is identical, the implementation differs in several ways:

Aspect MapLibre GL Leaflet
Coordinate order [lng, lat] [lat, lng]
Hover detection Layer events on route Transparent polyline overlay
Custom markers HTML elements L.divIcon or L.icon
Route rendering GeoJSON source + layers L.polyline or L.geoJSON
State updates setPaintProperty() Remove and re-add layers

The biggest difference: Leaflet doesn't support hover events on styled polylines as cleanly as MapLibre GL. We solve this with an invisible, wider polyline that captures mouse events.

Screenshot showing the Leaflet route editor with sidebar panel and numbered markers


Application State Management

The Leaflet demo uses a centralized state object. This keeps all mutable data in one place:

const state = {
    waypoints: [...INITIAL_WAYPOINTS],
    routeCoordinates: [],
    isLoading: false,
    isProcessingWaypoint: false,

    map: {
        routeLayer: null,
        floatingMarker: null,
        hoverLine: null,
        waypointMarkers: []
    }
};
Enter fullscreen mode Exit fullscreen mode

This pattern makes it easy to track what's happening: isLoading prevents hover interactions during API calls, isProcessingWaypoint is the operation lock we discussed in the MapLibre GL article.


Creating the Hover Detection Layer

Leaflet polylines with styling don't reliably capture mouse events at their edges. The solution: add an invisible, wider polyline on top:

function createHoverDetectionLine() {
    return L.polyline(state.routeCoordinates, {
        color: "transparent",
        weight: HOVER_DETECTION_WIDTH,
        opacity: 0,
        interactive: true
    }).addTo(map);
}
Enter fullscreen mode Exit fullscreen mode

The HOVER_DETECTION_WIDTH is set to 20 pixels, much wider than the visible route (8px outline + 5px main line). This gives users a generous target for hovering.

Screenshot showing the floating marker appearing when hovering over the route

The hover events attach to this invisible line:

hoverLine.on("mousemove", (e) => {
    if (shouldIgnoreHover()) return;

    hoverState.isHovering = true;
    showFloatingMarkerAt(e.latlng);
});

hoverLine.on("mouseout", () => {
    hoverState.isHovering = false;
    scheduleMarkerHide(hoverState);
});
Enter fullscreen mode Exit fullscreen mode

The Floating Marker with L.divIcon

MapLibre GL uses HTML elements directly for markers. Leaflet uses L.divIcon to achieve the same:

function createFloatingMarker() {
    const icon = L.divIcon({
        className: "",
        html: '<div class="floating-marker"></div>',
        iconSize: [20, 20],
        iconAnchor: [10, 10]
    });

    return L.marker([0, 0], {
        icon,
        draggable: true,
        opacity: 0,
        interactive: true
    }).addTo(map);
}
Enter fullscreen mode Exit fullscreen mode

The CSS handles the visual styling:

.floating-marker {
    width: 20px;
    height: 20px;
    background: #fff;
    border: 3px solid #2196F3;
    border-radius: 50%;
    cursor: grab;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

.floating-marker:active {
    cursor: grabbing;
    background: #2196F3;
}
Enter fullscreen mode Exit fullscreen mode

The :active pseudo-class changes the cursor and background on mousedown, providing immediate visual feedback when users interact with the marker.

Screenshot showing a new via point marker after dragging the floating marker


Waypoint Markers with Tooltips

Leaflet has built-in tooltip support. We use it to show interaction hints:

function createViaMarker(waypoint, index) {
    const color = getMarkerColor(index).replace('#', '%23');
    const icon = L.icon({
        iconUrl: `https://api.geoapify.com/v2/icon?type=awesome&color=${color}&text=${index + 1}&size=48&contentSize=20&scaleFactor=2&apiKey=${API_KEY}`,
        iconSize: [36, 48],
        iconAnchor: [18, 48]
    });

    const marker = L.marker([waypoint.lat, waypoint.lon], {
        icon,
        draggable: true
    }).addTo(map);

    marker.bindTooltip("Drag to change route<br>Click to remove", {
        direction: "top",
        offset: [0, -48]
    });

    return marker;
}
Enter fullscreen mode Exit fullscreen mode

The tooltip appears on hover without extra JavaScript. The offset positions it above the marker icon.

Screenshot showing a marker with tooltip "Drag to change route, Click to remove"

For origin and destination markers, the tooltip shows the location name instead:

const label = waypoint.type === "origin" ? "Origin" : "Destination";
marker.bindTooltip(`<strong>${waypoint.name}</strong><br>${label}`, {
    direction: "top",
    offset: [0, -48]
});
Enter fullscreen mode Exit fullscreen mode

When you click a via point, it's removed from the route and the path recalculates:

Screenshot showing the route after removing a via point


Building the Sidebar Panel

Unlike the MapLibre GL demo (which shows only an info bar), this Leaflet demo includes a full sidebar with a waypoint list:

function createWaypointListItem(waypoint, index) {
    const label = getWaypointLabel(waypoint, index);
    const canRemove = waypoint.type === "via";
    const removeButton = canRemove
        ? `<button class="waypoint-remove" onclick="removeWaypoint(${index})">×</button>`
        : "";

    return `
    <div class="waypoint-item ${waypoint.type}">
      <span class="waypoint-number-badge" style="background-color: ${getMarkerColor(index)}">${index + 1}</span>
      <span class="waypoint-label">${label}</span>
      <span class="waypoint-coords">${waypoint.lat.toFixed(5)}, ${waypoint.lon.toFixed(5)}</span>
      ${removeButton}
    </div>
  `;
}
Enter fullscreen mode Exit fullscreen mode

The sidebar provides an alternative way to remove via points (clicking the × button) and shows coordinates for each waypoint.

Screenshot showing the sidebar panel with waypoint list and route info


Explore the Demo

The demo includes all the features from the MapLibre GL version, plus a sidebar panel:

  • Drag any marker to reposition a waypoint
  • Hover the route to see the floating marker
  • Drag the floating marker to add a via point
  • Click a via point to remove it
  • Use the sidebar to see waypoint details and remove points
  • Click Reset to restore the original route

The sidebar updates automatically as you edit the route, showing distance, duration, and waypoint count.

👉 Try the live demo:


Summary

Implementing drag-and-drop route editing in Leaflet requires different techniques than MapLibre GL, but achieves the same user experience:

  1. Invisible hover layer - A transparent, wider polyline captures mouse events reliably
  2. L.divIcon for custom markers - CSS-styled div elements work like MapLibre GL's HTML markers
  3. Built-in tooltips - Leaflet's bindTooltip() simplifies interaction hints
  4. Centralized state - A single state object keeps the code organized
  5. Sidebar integration - HTML panels are easy to sync with map state

When to use Leaflet vs MapLibre GL:

  • Leaflet: Simpler API, extensive plugin ecosystem, great for raster tiles
  • MapLibre GL: Better performance with complex routes, vector tiles, 3D views

Both achieve the same UX. Choose based on your existing stack and requirements.

Useful links:


FAQ

Q: Why use a transparent polyline for hover detection instead of the visible route?

A: Leaflet's polyline hover detection is based on the line's weight. A 5px line is hard to hover precisely. The transparent 20px overlay provides a much larger target while keeping the visual route thin and clean.

Q: Can I use the same floating marker approach with L.circleMarker?

A: Yes, but L.circleMarker has limitations with dragging. Using L.marker with L.divIcon gives you full control over styling and drag behavior.

Q: Why does the demo use inline onclick handlers in the waypoint list?

A: For simplicity in the demo. In production, use event delegation: attach one listener to the list container and check e.target to determine which button was clicked.

Q: Can I persist the edited route to localStorage?

A: Yes. Serialize state.waypoints to JSON and save it. On page load, check localStorage and restore the waypoints before calling fetchAndRenderRoute().


Try It Now

👉 Open the Live Demo

Sign up at geoapify.com to get your API key and start building route editors with Leaflet.

Top comments (0)