GMaps JS Geocode: Using/Passing Variables With Asynchronous Geocode Function?

后端 未结 1 725
不思量自难忘°
不思量自难忘° 2021-01-03 06:48

I have an array list of location objects, and I am using some of them to build a full address, and then geocode that. Once I receive the OK status I am then placing a marke

相关标签:
1条回答
  • 2021-01-03 07:11

    The simplest thing is probably to create a local scope block within your loop so that locationName actually refers to a different variable for every time you add a delegate/anonymous function to do the geocoding. Placing the var in the loop does not create a new instance of the variable, the var declaration essentially gets moved to the top of the enclosing scope block.

    for(var i=0; i<myObjList.length; i++){
        var fullAddress = myObjList[i].Address + ", " + myObjList[i].City + ", " + myObjList[i].State + ", " + myObjList[i].Zip;
        //begin scope block
        (function(){
            var locationName = myObjList[i].LocationName;
            var yourObject = myObjList[i];
             //etc.
            geocoder.geocode( ...);
        //end scope block
        })();
    }
    

    Edit:

    Or if you were using some framework/ that allows you to pass an anonymous function to execute code for each item in an array, you get that kind of scoping issue taken care for you automatically.

    0 讨论(0)
提交回复
热议问题