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:
- Routing API - calculate route between waypoints
- Map Tiles API - raster map tiles
- Map Marker Icon API - numbered waypoint markers
What you will learn:
- Key differences between Leaflet and MapLibre GL for route editing
- Creating invisible hover detection layers in Leaflet
- Using
L.divIconfor custom floating markers - Managing application state with a clean architecture
- Building a sidebar panel for waypoint management
Table of Contents
- Leaflet vs MapLibre GL: Key Differences
- Application State Management
- Creating the Hover Detection Layer
- The Floating Marker with L.divIcon
- Waypoint Markers with Tooltips
- Building the Sidebar Panel
- Explore the Demo
- Summary
- 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.
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: []
}
};
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);
}
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.
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);
});
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);
}
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;
}
The :active pseudo-class changes the cursor and background on mousedown, providing immediate visual feedback when users interact with the 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;
}
The tooltip appears on hover without extra JavaScript. The offset positions it above the marker icon.
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]
});
When you click a via point, it's removed from the route and the path recalculates:
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>
`;
}
The sidebar provides an alternative way to remove via points (clicking the × button) and shows coordinates for each waypoint.
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:
- Invisible hover layer - A transparent, wider polyline captures mouse events reliably
- L.divIcon for custom markers - CSS-styled div elements work like MapLibre GL's HTML markers
-
Built-in tooltips - Leaflet's
bindTooltip()simplifies interaction hints - Centralized state - A single state object keeps the code organized
- 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:
- Geoapify Routing API Documentation
- Routing API Playground
- Map Marker Icon API
- Leaflet Marker Documentation
- Leaflet Polyline Documentation
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
Sign up at geoapify.com to get your API key and start building route editors with Leaflet.






Top comments (0)