How to mark and highlight with a line all road nearby me around 10m in javascript?

Here is my code can anyone fix it?

   // Function to fetch nearby roads and color them
    function fetchRoads(lat, lng) {
        console.log("Fetching nearby roads...");
        var query = `[out:json];way(around:50, ${lat}, ${lng})[highway];out;`;
        var url = `https://overpass-api.de/api/interpreter?data=${encodeURIComponent(query)}`;

        console.log("Query URL:", url); // Add this line to check the constructed URL

        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                console.log("Roads data:", data);
                console.log("Roads count:", data.elements.length);
                processRoadData(data);
            })
            .catch(error => {
                console.error('Error fetching road data:', error);
            });
    }

    // Function to process retrieved road data and log the coordinates of every road
    function processRoadData(data) {
        data.elements.forEach(element => {
            if (element.type === "way") {
                var roadCoordinates = []; // Array to store coordinates of the road
                console.log("Number of nodes for road:", element.nodes.length); // Log the number of nodes
                element.nodes.forEach(nodeId => {
                    var node = data.elements.find(e => e.type === "node" && e.id === nodeId);
                    if (node) {
                        roadCoordinates.push([node.lat, node.lon]); // Store the coordinates
                        // Log the coordinates to the console
                        console.log("Road Coordinate:", [node.lat, node.lon]);
                        // Create a marker at the node's location
                        L.marker([node.lat, node.lon]).addTo(map).bindPopup('Road Point 📍');
                    }
                });
                // Log the coordinates array for the entire road
                console.log("Road Coordinates:", roadCoordinates);
            }
        });
    }

1 post - 1 participant

Read full topic


Ce sujet de discussion accompagne la publication sur https://community.openstreetmap.org/t/how-to-mark-and-highlight-with-a-line-all-road-nearby-me-around-10m-in-javascript/111238