Search code examples
javajavascriptmapsarcgisesri

Map on click to get multiple coordinates


I was having some problem when trying to plot two markers on the map and get the start and end coordinates. Here is the code:

function showBusFilter(){
 map.on("click", function (evt) { 
     var counter = 1;
     if(counter == 1){
         var startLoc = (evt.mapPoint.x, evt.mapPoint.y);
         counter++;
     }
     else if(counter == 2){
         var endLoc = (evt.mapPoint.x, evt.mapPoint.y);
         counter = 1;
     }
     console.log(startLoc);
     console.log(endLoc);
     plotBusRouteByMarker(startLoc, endLoc);
 });    
}

I am using a counter variable to differentiate between first and second marker. So basically what I am trying to do is when the map on first click, I am getting the startLoc. Then, when the map clicked for the second time, then I get the endLoc. After getting both of them, then I pass them as parameter for the routing method.

However, with these codes, when I click on the map, it just populate the startLoc with coordinate and endLoc with undefined and execute the plotBusRouteByMarker().

Any ideas?

Thanks in advance.


Solution

  • This is because whenever you click on map the 'counter' variable always be 1 and hence each time startLoc will be assigned.
    You can instead take help of closure concept to remember the 'counter' like below

    var counter = 0;
    
    function showBusFilter() {
        map.on("click", function(evt) {//anonymous fn
                counter ++ ;//now this will point to global counter and hence will not claimed by GC after fn execution
                if(counter === 1) {
                    var startLoc = (evt.mapPoint.x, evt.mapPoint.y);
                } else if(counter === 2) {
                    var endLoc = (evt.mapPoint.x, evt.mapPoint.y);
                    counter = 0;
                }
                plotBusRouteByMarker(startLoc, endLoc);
            });
    }