开发者

How to ensure the 'correct' variable is used in a loop with anonymous functions?

开发者 https://www.devze.com 2023-02-17 19:37 出处:网络
We have followed Tom Anthony\'s tutorial to calculate a geocode from a UK postcode to plot a marker on a Google Map. This has worked fine, but now we wish to add a popup when you click on a location.

We have followed Tom Anthony's tutorial to calculate a geocode from a UK postcode to plot a marker on a Google Map. This has worked fine, but now we wish to add a popup when you click on a location. So we updated our function to place a marker and original usePointFromPostcode code to take in a description:

function usePointFromPostcode(postcode, description, callbackFunction) {

  localSearch.setSearchCompleteCallback(null, 
    function() {

      if (localSearch.results[0]) {    
        var resultLat = l开发者_如何学CocalSearch.results[0].lat;
        var resultLng = localSearch.results[0].lng;
        var point = new GLatLng(resultLat,resultLng);
        callbackFunction(point, description);
      }else{
        alert("Postcode not found!");
      }
    });  

  localSearch.execute(postcode + ", UK");
}
// loop through the array of postcodes to output markers
for(var i=0; i<postcodes; i++) {
    usePointFromPostcode(postcodes[i], descriptions[i], placeMarkerAtPoint);
}

However, whilst the page loads without error, the markers all have the same description - that of the last item in the array. I believe this is due to a closure, or rather a lack of one, but am unable to hack out the solution. How can we get the descriptions in sync with the points?


If localsearch.execute initiates a search but returns before the search is complete, then that would explain the behaviour. Two possible solutions. Create a separate GlocalSearch object for each query or delay issuing the second query until the first is complete, etc.

I don't know enough about the GlocalSearch class to say if the former is sensible. If it is, you presumably will have several searches running in parallel that may finish in arbitrary order.

To do the later: Alter your callback to set a global flag done to true. Before initiating the first search, set done to false. After initiating the first search, set a timeout. The code executed by the timeout does the following: if done is now true, it sets done to false and initiates the second search. Otherwise, it simply repeats the same timeout. And of course this sort of thing repeats until all searches are complete, at which point the time out code initiates whatever you want to do after that loop. See http://www.ehow.com/how_4847411_simulate-whilesleep-loop-javascript.html for a short article that may be helpful.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号