Search code examples
reactjsmapbox-gl-jsmapbox-glreact-map-gl

Connect markers with a polyline in Mapbox GL


I'm developing a web application using Mapbox GL, more specifically, its binding for React, react-map-gl.

One of the planned functionalities for the app is adding markers and connecting them.

However, I'm having trouble connecting markers.

I want to start drawing the line when I click on a marker, add a breakpoint to the line when I click elsewhere and finish the line when I click on another marker.

What can I use for this?


Solution

  • What I ended up doing was using an EditableGeoJsonLayer with the features for both the markers and the connections between them as follows:

    data: {
        type: "FeatureCollection",
        features: markers.flatMap((marker) => {
            // Map markers
            let features = [
                {
                    geometry: {
                        type: "Point",
                        coordinates: marker.coordinates
                    },
                    type: "Feature",
                    node: marker
                }
            ];
    
            // Map connections
            if (marker.connections.length > 0) {
                features = features.concat(
                    marker.connections.flatMap((endMarker) => [
                        {
                            geometry: {
                                type: "LineString",
                                coordinates: [
                                    marker.coordinates,
                                    endMarker.coordinates
                                ]
                            },
                            type: "Feature"
                        }
                    ])
                );
            }
    
            return features;
        })
    }