2

I want to set global variable from function and loop ajax to get distance. However the nearestIndex variable is always undefined.

First solution I got was to use async: false - this is work in my pc browser, but this project is webservice to android, and this solution not work to webview.

And of course async: false not recommended. I need this example in my case, I've been looking for this problem in stack overflow, but i always failed to understand about callback.

var allDestination = ["A", "B", "C"];
var nearestIndex;

function getNearest(){
 var from = myPosition.getLatLng().lat + "," + myPosition.getLatLng().lng;
 var tempDistance;
 for(var i=0; i<allDestination.length; i++){
  var destination = allDestination[i].getLatLng().lat + "," + allDestination[i].getLatLng().lng;
  $.ajax({
            type: "GET",
            url: "http://localhost:8989/route?point=" + from + "&point=" + destination + "&points_encoded=false&instructions=false",
            dataType: 'json',
            contentType: "application/json",
            success: function (data) {
             var distance = data.distance;
             if(i == 0){
              tempDistance = distance;
              nearestIndex = i;
             } else {
              if(distance < tempDistance){
               tempDistance = distance;
               nearestIndex = i;
              }
             }
            }
        });
 }
}

function onMapClick(e) {
 myPosition.setLatLng(e.latlng);         
 myPosition.addTo(map);
 getNearest();
 allDestination[nearestIndex].addTo(map);
}
Nicholas Smith
  • 674
  • 1
  • 13
  • 27
fadli hudaya
  • 97
  • 2
  • 7

2 Answers2

0

I ever have got the same problem like you, it because asincrounous function cant return anything. so I think you shoud inject allDestination[nearstIndex].addTo(map); into ajax success

if(i == 0){
                tempDistance = distance;
                allDestination[i].addTo(map);
            } else {
                if(distance < tempDistance){
                    tempDistance = distance;
                    allDestination[i].addTo(map);
                }
            }

or you create function to handle ajax success,,, CMIIW

Adzimzf
  • 181
  • 2
  • 11
  • If i inject allDestination[i].addToMap(map) in ajax success, all of destination will show in map, i just want one of them not all. I need the minimal distance. I dont know how to create function to handle ajax succes, can you give some example? – fadli hudaya Jan 25 '17 at 07:08
0

As you are dealing with Async call; your relevant code has to get called from success handler of ajax call as follows:

var allDestination = ["A", "B", "C"];
var nearestIndex;
var tempDistance;
var successReceived = 0; //counter to keep watch on ajax success callback

//modify the function signature to receive index as well as callback function
function getNearest(index, callbackFunction) {
  var from = myPosition.getLatLng().lat + "," + myPosition.getLatLng().lng;

    var destination = allDestination[index].getLatLng().lat + "," + allDestination[index].getLatLng().lng;
    $.ajax({
      type: "GET",
      url: "http://localhost:8989/route?point=" + from + "&point=" + destination + "&points_encoded=false&instructions=false",
      dataType: 'json',
      contentType: "application/json",
      success: function(data) {
          successReceived++; //increment the success counter 
        var distance = data.distance;
        if (index == 0) {
          tempDistance = distance;
          nearestIndex = index;
        } else {
          if (distance < tempDistance) {
            tempDistance = distance;
            nearestIndex = index;
          }
        }

        //check if we got all the ajax response back. If yes then call the callback function
        if(successReceived == allDestination.length && typeof callbackFunction == 'function')
        {
            callbackFunction();
        }
      }
    });

}

function onMapClick(e) {
  myPosition.setLatLng(e.latlng);
  myPosition.addTo(map);

  for (var i = 0; i < allDestination.length; i++) {
      //pass the current index and callback function
      getNearest(i,function(){
          allDestination[nearestIndex].addTo(map);
      });
  }

}
vijayP
  • 11,432
  • 5
  • 25
  • 40
  • Thank you its works sir. So the concept is if alldestination length = 3, we call the callback function 3 times? – fadli hudaya Jan 25 '17 at 10:17
  • welcome...! its like: we pass the callback function 3 times but its gets invoked only once i.e. at the very last `success` execution. – vijayP Jan 25 '17 at 10:52