DEV Community

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

Posted on

How to Edit Routes with Drag and Drop on a MapLibre GL Map

Route planning applications need more than just displaying a route. Users expect to modify routes interactively: drag a waypoint to a different location, add a stop by clicking on the route, or remove an unwanted via point. These interactions feel natural when done right, but implementing them requires careful attention to UX details.

This tutorial shows how to build a drag-and-drop route editor with MapLibre GL. We'll focus on the interaction patterns that make route editing feel intuitive and responsive.

APIs used:

What you will learn:

  • Designing intuitive drag-and-drop interactions for routes
  • Adding via points by hovering and dragging on the route line
  • Handling concurrent operations to prevent race conditions
  • Finding the optimal insertion point for new waypoints
  • Creating a floating marker that follows the route

Table of Contents

  1. The UX Goal: Natural Route Editing
  2. Set Up the Map and Initial Route
  3. Create Draggable Waypoint Markers
  4. Add the Floating Marker for Via Points
  5. Find the Best Insertion Point
  6. Prevent Concurrent Operations
  7. Explore the Demo
  8. Summary
  9. FAQ

The UX Goal: Natural Route Editing

Before writing code, let's define what makes route editing feel natural:

Key UX principles:

  • Drag markers to reposition - Users expect to grab any waypoint and move it
  • Hover on route to add stops - A floating marker appears when hovering the route line, inviting users to drag it to add a via point
  • Click via points to remove - Simple removal without confirmation dialogs for intermediate stops
  • Visual feedback - Cursor changes, marker highlights, and smooth transitions
  • No accidental actions - Operation locks prevent double-clicks from creating duplicate waypoints

The interaction flow:

  1. User hovers over the route line → floating marker appears
  2. User drags the floating marker → marker becomes a new via point
  3. User drags any marker → route recalculates
  4. User clicks a via point → point is removed

Screenshot showing the initial route with numbered markers (1 and 2) on the map


Set Up the Map and Initial Route

Start with a MapLibre GL map and define the initial waypoints:

const API_KEY = "YOUR_API_KEY";

let waypoints = [
    {id: generateWaypointId(), lat: 48.8584, lon: 2.2945, type: "start"},
    {id: generateWaypointId(), lat: 48.8738, lon: 2.2950, type: "end"}
];

const map = new maplibregl.Map({
    container: "map",
    style: `https://maps.geoapify.com/v1/styles/osm-bright/style.json?apiKey=${API_KEY}`,
    center: [2.32, 48.865],
    zoom: 13
});

map.on("load", async () => {
    await fetchRoute();
});
Enter fullscreen mode Exit fullscreen mode

Each waypoint has a unique id (not just an array index). This is important because when users remove waypoints, array indices shift, but IDs remain stable.

The route uses two layers: an outline for hover detection and the main route line:

// Route outline (wider, for better hover detection)
map.addLayer({
    id: "route-outline",
    type: "line",
    source: "route",
    paint: { "line-color": "#1565C0", "line-width": 8 }
});

// Main route line
map.addLayer({
    id: "route",
    type: "line",
    source: "route",
    paint: { "line-color": "#2196F3", "line-width": 5 }
});
Enter fullscreen mode Exit fullscreen mode

Tip: The wider outline layer (8px vs 5px) makes it easier to hover on the route, especially on mobile or with less precise input devices.


Create Draggable Waypoint Markers

Each waypoint gets a numbered marker. The key is capturing the waypoint id in the closure, not the array index:

const waypointId = wp.id; // Capture ID, not index

const marker = new maplibregl.Marker({element, draggable: true, anchor})
    .setLngLat([wp.lon, wp.lat])
    .addTo(map);
Enter fullscreen mode Exit fullscreen mode

This prevents bugs when waypoints are added or removed. Array indices shift, but IDs remain stable.

Click to remove via points:

element.addEventListener("click", async (e) => {
    e.stopPropagation();
    await withWaypointLock(async () => {
        const currentIndex = waypoints.findIndex(w => w.id === waypointId);
        if (currentIndex !== -1 && waypoints[currentIndex].type === "via") {
            waypoints.splice(currentIndex, 1);
            await fetchRoute();
        }
    });
});
Enter fullscreen mode Exit fullscreen mode

Drag to update position:

marker.on("dragend", async () => {
    await withWaypointLock(async () => {
        const currentIndex = waypoints.findIndex(w => w.id === waypointId);
        if (currentIndex !== -1) {
            const {lng, lat} = marker.getLngLat();
            waypoints[currentIndex].lat = lat;
            waypoints[currentIndex].lon = lng;
            await fetchRoute();
        }
    });
});
Enter fullscreen mode Exit fullscreen mode

The marker icons are generated with the Map Marker Icon API, including tooltips for available actions:

el.src = `https://api.geoapify.com/v2/icon?type=awesome&color=${color}&text=${index + 1}&size=48&contentSize=20&scaleFactor=2&apiKey=${API_KEY}`;
Enter fullscreen mode Exit fullscreen mode

Screenshot showing a marker being hovered with tooltip "Drag to move • Click to remove

When clicking a via point, it's removed from the route:

Screenshot showing the route after clicking a via point - the marker disappears and route recalculates


Add the Floating Marker for Via Points

The floating marker appears when hovering the route. It's a simple circle that invites users to drag:

const el = document.createElement("div");
el.style.width = "20px";
el.style.height = "20px";
el.style.background = "#fff";
el.style.border = "3px solid #2196F3";
el.style.borderRadius = "50%";
el.style.cursor = "grab";
el.style.opacity = "0";

floatingMarker = new maplibregl.Marker({element: el, draggable: true, anchor: "center"})
    .setLngLat([0, 0]).addTo(map);
Enter fullscreen mode Exit fullscreen mode

Show on route hover:

map.on("mousemove", "route-outline", (e) => {
    if (isProcessingWaypoint || isDragging) return;

    const nearestPoint = findNearestPointOnRoute(e.lngLat);
    floatingMarker.setLngLat(nearestPoint);
    el.style.opacity = "1";
});
Enter fullscreen mode Exit fullscreen mode

The marker snaps to the nearest point on the route, not the cursor position. This provides visual feedback that the waypoint will be placed on the route.

Screenshot showing the white floating marker appearing on the route when hovering

Convert to via point on drag end:

floatingMarker.on("dragend", async () => {
    const {lng, lat} = floatingMarker.getLngLat();
    await withWaypointLock(async () => {
        const insertIndex = findBestIndex(lat, lng);
        waypoints.splice(insertIndex, 0, {
            id: generateWaypointId(),
            lat,
            lon: lng,
            type: "via"
        });
        await fetchRoute();
    });
});
Enter fullscreen mode Exit fullscreen mode

Visual state changes during drag (background color turns blue) give clear feedback that an action is in progress.

Screenshot showing a new numbered marker (3) appearing after dragging the floating marker


Find the Best Insertion Point

When a user adds a via point, we need to determine where in the waypoint list to insert it. The algorithm finds the segment closest to the new point:

function findBestIndex(lat, lon) {
    let bestIndex = 1;
    let minDist = Infinity;

    for (let i = 0; i < waypoints.length - 1; i++) {
        const dist = distToSegment(
            {lat, lon},
            {lat: waypoints[i].lat, lon: waypoints[i].lon},
            {lat: waypoints[i + 1].lat, lon: waypoints[i + 1].lon}
        );

        if (dist < minDist) {
            minDist = dist;
            bestIndex = i + 1;
        }
    }

    return bestIndex;
}
Enter fullscreen mode Exit fullscreen mode

The distToSegment() function calculates the perpendicular distance from a point to a line segment. This ensures the new waypoint is inserted between the correct existing waypoints, maintaining logical route order.


Prevent Concurrent Operations

A common bug in interactive applications: users double-click or trigger multiple operations before the first completes. We use an operation lock:

let isProcessingWaypoint = false;
const OPERATION_COOLDOWN_MS = 300;

async function withWaypointLock(operation) {
    if (isProcessingWaypoint) return false;

    isProcessingWaypoint = true;
    try {
        await operation();
        return true;
    } finally {
        setTimeout(() => {
            isProcessingWaypoint = false;
        }, OPERATION_COOLDOWN_MS);
    }
}
Enter fullscreen mode Exit fullscreen mode

Every waypoint modification (add, remove, drag) goes through withWaypointLock(). This prevents:

  • Double-clicking a via point from triggering two removals
  • Dragging while another operation is in progress
  • Race conditions between API calls

The 300ms cooldown gives the UI time to update before accepting new input.


Explore the Demo

The interactive demo lets you experience all the editing features:

  • Drag any marker to reposition a waypoint
  • Hover the route to see the floating marker appear
  • Drag the floating marker to add a new via point
  • Click a via point (numbered 2, 3, etc.) to remove it
  • Watch the info panel update with distance, time, and point count

The route recalculates automatically after each change. Try adding multiple via points to create a complex route, then simplify it by clicking to remove stops.

👉 Try the live demo:


Summary

Building a drag-and-drop route editor requires attention to both technical implementation and user experience. This tutorial covered:

  1. Unique waypoint IDs - Using IDs instead of array indices prevents bugs when waypoints are added/removed
  2. Floating marker pattern - A marker that appears on route hover invites users to add via points
  3. Segment-based insertion - Finding the optimal position for new waypoints maintains route logic
  4. Operation locking - Preventing concurrent modifications avoids race conditions
  5. Visual feedback - Cursor changes, opacity transitions, and color changes communicate state

Key UX takeaways:

  • Make interactions discoverable (floating marker appears on hover)
  • Provide clear feedback (cursor changes, visual transitions)
  • Prevent accidental actions (operation locks, confirmation through drag vs click)
  • Keep it responsive (route recalculates immediately)

Useful links:


FAQ

Q: Why use unique IDs instead of array indices for waypoints?

A: Array indices shift when waypoints are added or removed. If a marker's click handler references index 2, and the user removes index 1, the handler now points to the wrong waypoint. Unique IDs remain stable regardless of array changes.

Q: How do I prevent the floating marker from appearing over existing waypoint markers?

A: The floating marker only appears when hovering the route line layer (route-outline). Waypoint markers have a higher z-index, so they receive mouse events first. When hovering a waypoint, the route hover event doesn't fire.

Q: Can I limit the number of via points users can add?

A: Yes. In the dragend handler for the floating marker, check waypoints.length before inserting. If it exceeds your limit, show a message instead of adding the point.

Q: Why is there a 300ms cooldown after operations?

A: The cooldown prevents rapid successive operations that could cause race conditions. It also gives the UI time to update, providing visual feedback that the action completed before accepting new input.

Q: How would I add undo/redo functionality?

A: Maintain a history array of waypoint states. Before each modification, push a copy of the current waypoints array to history. Undo pops from history and restores that state. Redo requires a separate "future" stack.

Q: Can I save the edited route?

A: Yes. The waypoints array contains all the data needed to recreate the route. You can serialize it to JSON and store it in localStorage, a database, or send it to your backend.

Q: How do I make this work on touch devices?

A: MapLibre GL handles touch events automatically for draggable markers. The floating marker requires additional handling - consider showing it on tap instead of hover, or using a long-press gesture to add via points.


Try It Now

👉 Open the Live Demo

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

Top comments (0)