问题
I'm using reverseGeo method of manager nokia.places.search.manager (HERE API) to retrieve information about a coordinate. It works fine in my case when displaying the info for one point. But when I've more than one point all my point get the info of the last one.
In fact I don't use infobubble to display address info inside the onComplete method as it's done in the example provided.
I've stored all my markers(an extension of nokia.maps.map.Marker that embeded an InfoBuble) inside a key/value global var. So inside the onComplete method, I want to update the right marker.
Below this is how I invoke the search service:
searchManager.reverseGeoCode({
latitude: lat,
longitude: lng,
onComplete: function(data, status, requestId){
processResults(data, status, requestId, myID);
}
});
where myID is the value that allow to retrieve the right marker to update with address info.
Regards
回答1:
You can do that with any JavaScript callback by using immediately invoked function expression.
Your code should look something like that:
searchManager.reverseGeoCode({
latitude: lat,
longitude: lng,
onComplete: (function(localID) {
return function(data, status, requestId) {
processResults(data, status, requestId, localID);
};
})(myID)
});
To understand this example you need good comprehension of closures and above mentioned immediately invoked function expressions syntax.
回答2:
I had a similar just today, and it's rather obscure. Along the same lines suggested by Andrzej Duś, you have a problem with scope of the callback function. The parameters in the callback are evaluated at the time the callback is executed, which is why it always executes with the parameters passed to the last one. You need the callback function to execute with the parameters (i.e., myID) of the particular iteration in your enclosing loop.
One way to do this is to create a new function, like this:
var f = new Function('myCallbackFunction(' + myID + ')');
exampleExternalFunction(f);
Or, using your example,
var f= new Function('data', 'status', 'requestId',
'processResults(data, status, requestId,' + myID + ')'
... other code ...
onComplete: f
...
I may not have the above quite right for your case. Look up the details of JavaScript "new Function()" to understand this a little better.
来源:https://stackoverflow.com/questions/18190043/is-there-a-way-to-associate-the-reponse-and-query-while-invoking-nokia-reverse-g