Consider the following example:
var features = [];
$.getJSON(annotations_url, function(data) {
$.each(data, function(key, val) {
features.push(wkt_parser.read(val.annotation.wkt_data));
// at this point, "features" contains objects
});
});
annotationLayer.addFeatures(features);
// here, it is empty again
Here, I expect features to continuously grow. However, in the last line, features is empty again.
Why is that and how would I correctly push values to features from within the $.each (or rather the anonymous function inside)?
The
$.getJSONcall is asynchronous, soannotationLayer.addFeaturesis probably being executed before the JSON request has finished. Call theaddFeaturesmethod inside the$.getJSONcall, after the.eachloop.If you need to perform more stuff with
features, consider creating a new function (which includes theaddFeaturesmethod you need to call), and then call this new function after the.eachloop inside the$.getJSONcall.