Manually selecting locations on map for leaflet routing machine

66 Views Asked by At

I am currently using the leaflet routing machine in one of my test application, the idea here is to pick locations manually by selecting on the map for each start and end destination

I've created two separate buttons Start_pick_point for start and End_pick_point for end waypoints. Here is the part of the code where i've added event listeners.

When i initially click on any button (start/end) the location correctly gets selected and assigns the decoded location to its corresponding waypoint input field, but i am failing to register the 2nd button press

How can i fix this ?

Note! this works as expected if i comment out the line routingControl.spliceWaypoints( )

var startPickPointBtn = document.getElementById('Start_pick_point');
var endPickPointBtn = document.getElementById('End_pick_point');

startPickPointBtn.addEventListener('click', function() {  
    console.log('Start Button  clicked!'); 
    map.once('click', function (e) {
        console.log('Start point selected');        
        routingControl.spliceWaypoints(0, 1, e.latlng);
    });
   
});

endPickPointBtn.addEventListener('click', function() {       
    console.log('End Button  clicked!');         
    map.once('click', function (e) {                 
        console.log('End point selected');
        routingControl.spliceWaypoints(routingControl.getWaypoints().length - 1, 1, e.latlng);
    });    
});



routingControl = L.Routing.control({
    // waypoints: [
    //     L.latLng(42.49152098732, -83.41745942217),
    //     L.latLng(42.466764547938, -83.431811743515)
    // ] //Debug,            
    waypoints: [null],
    geocoder: L.Control.Geocoder.nominatim(),
    routeWhileDragging: true,
    reverseWaypoints: true,
    showAlternatives: false,
    addWaypoints: true,
    annotations: true,
    lineOptions: {
            styles: [
                {className: 'animate', color: 'black', weight: 4 }// Adding animate class
            ] 
        }, 
    altLineOptions: {
        styles: [
            {className: 'animate', color: 'white', weight: 4, opacity: 0.5 }
        ]
    },              
    createMarker: function(i, wp, nWps) {
        if (i === 0 ) {
            return L.marker(wp.latLng, {icon: startIcon, draggable: true });
        }
        else if (i > 0 && i < nWps - 1)
        {
            return L.marker(wp.latLng, {icon: midIcon, draggable: true });
        }
        else if (i === nWps - 1)
        {                       
            return L.marker(wp.latLng, {icon: endIcon, draggable: true  });
        }
    },
})
0

There are 0 best solutions below