AnsweredAssumed Answered

Looping with GeometryService Distance (deferred problem?)

Question asked by zaloudek on Aug 22, 2014
Latest reply on Sep 4, 2014 by zaloudek

OK, there has GOT to be a way to do this that I'm just not seeing on my own.


I have a feature layer of points (stations) in my map.  The task is to find the three points in the feature layer that are closest to where the user clicks on the map (and then display data from those stations, etc...).


So far, I have been able to select all points within a 50-mile radius circle of the clicked-point, and I have saved the points' names/IDs and locations (as point geometry) to an array.


Next, I want to loop through the objects in the array I've just made, and for each, find its distance from the clicked-point (using the geometryService.distance method).  Then I add the station's name and distance to a new array/list.  My plan from there is to figure out which three stations are the closest, and get the data I need to display, etc.


My problem is that the code is looping through the array faster than it can figure out each distance.  In my second array/list, every distance has the same station name, which happens to be the name of the last station in the first array.  I know that the result of the geometryService.distance method is a deferred object.  I've been trying to educate myself on these.  I think I get the jist of deferreds, but I can't figure out how to make them work for me here.  I have seen suggestions by some to use a deferred list, but it appears that you have to know how many items you want in that list beforehand.  In my case, I don't know exactly how many points will be within that 50-mile radius of the user's clicked-point.


Here is my javascript code as it stands.  At this point, my feature layer (named fLayer) already has the points within the 50-mile radius selected.


var selGraphics = fLayer.getSelectedFeatures();
var feature;
list = [];
for (i = 0; i < selGraphics.length; i++) {
    var stnname;
    feature = selGraphics[i];
    stnname = feature.attributes["Name"];
    uoid = feature.attributes["uid"];
    ptloc = feature.geometry;
    list.push({name:stnname, uid:uoid, loc:ptloc});                            
console.log('outside first loop now');

distlist = [];
for (i in list)  {
    station = list[i]
    ptloc = station.loc;
    distParams.geometry2 = ptloc;
    thisdist = geometryService.distance(distParams, function(distance) {
        console.log(, distance);
        distlist.push({, dist:distance});
console.log('outside second loop now');


BTW, I am much more comfortable with python than I am with javascript/html, hence my personal need to use lists/arrays.  If there is a better way to deal with this I'm open to suggestion!