I am loading a geoJSON file using ajax so that I can push the coordinates of the geoJSON MultiPoint feature that is in the file into a (global) array for use in another function. I am having a problem with my callback function, I think. In the code below, I intend to load the data file and push the data pertaining to certain whales into the multipointCoords array. This works fine, but multipointCoords array is not available globally while whales is available. This is confusing me.
This code is also using OpenLayers.
var whales = {};
var multipointCoords = [];
$.getJSON('data/BW2205005.geojson', function(data) {
data.features.forEach(function(feature) {
if (!whales.hasOwnProperty(feature.properties.name)) {
whales[feature.properties.name] = {
"type": "FeatureCollection",
"features": []
};
}
whales[feature.properties.name].features.push(feature);
whales["Free Willy"].features.forEach(function(feature) {
multipointCoords.push(feature.geometry.coordinates);
});
console.log(multipointCoords[0][0]); // gives the right coordinate
});
});
console.log(whales); // is defined
console.log(multipointCoords[0][0]); // is undefined
I have studied the following and still can't fix it:
How to load Open layers 3 geojson vector layer with bbox?
How do I return the response from an asynchronous call?
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
http://api.jquery.com/jQuery.getJSON/
Thanks for any help.
While making ajax calls, we are uncertain about when the
success
callback will fire, hence we usercallbacks
in such situations. And pass function as anargument
to the called function. In callback function we can pass the data retrieved inajax response
. I could see you are usingglobal-variable
in your snippet but you are using them synchronously, in that case value ofglobal-variable
is not updated(Values used before ajax success callback)
Try this:
function geoJSON(callback) {
var whales = {};
var multipointCoords = [];
$.getJSON('data/BW2205005.geojson', function(data) {
data.features.forEach(function(feature) {
if (!whales.hasOwnProperty(feature.properties.name)) {
whales[feature.properties.name] = {
"type": "FeatureCollection",
"features": []
};
}
whales[feature.properties.name].features.push(feature);
whales["Free Willy"].features.forEach(function(feature) {
multipointCoords.push(feature.geometry.coordinates);
});
if (typeof callback === 'function') {
callback(whales, multipointCoords);
}
});
});
}
geoJSON(function(whales, multipointCoords) {
console.log(whales);
console.log(multipointCoords);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments