I am having trouble with a seemingly simple problem. I am pulling data from an external JSON file and need to loop through all the objects and return their values to use in another function. Here is what I have so far...
var geo;
function getCountry(){
$.getJSON('country.json', function(res) {
$.each(res, function(key, val) {
for(var i = 0; i < val.length; i++) {
geo = val[i].geometry.coordinates;
return geo;
}
})
});
}
function mapIt() {
getCountry();
$(".container").mapael({
map : {
name : "world_countries", // name of JS file
},
plots: {
'Random': {
latitude: geo[0],
longitude: geo[1]
}
}
});
}
mapIt();
Essentially, I am getting the latitude and longitude of a specific country with the first function and am trying to return the value (geo, which is an array containing the lat/long) and use it in the second function. I thought that I could maybe call the getCountry function within the mapIt function and it would store the variable.
Any suggestions/help would be greatly appreciated thank you so much!
EDIT: Here is some of the JSON:
{
"world": [
{
"properties": {
"sr_subunit": "Zimbabwe",
"sr_brk_a3": "ZWE",
"countries": "ZW",
"scalerank": 0
},
"geometry": {
"type": "Point",
"coordinates": [
29.851884620879,
-19.002536710201
]
}
},
{
"properties": {
"sr_subunit": "Samoa",
"sr_brk_a3": "WSM",
"countries": "WS",
"scalerank": 0
},
"geometry": {
"type": "Point",
"coordinates": [
-172.404145,
-13.631557
]
}
}
]
}
The problem here is that you don't seem to understand how asynchrony works. The code after your getCountry()
call runs long before your getJSON
callback does, so it is working with a geo
value of undefined
. I don't really understand what you are trying to do there when your JSON has multiple pairs of coordinates and you're only trying to actually use one, but here is how you could operate on just the first pair:
function getCountry(){
$.getJSON('country.json', function(res) {
var country = res.world[0],
coords;
if (country) {
coords = country.geometry.coordinates;
mapCoordinates(coords[0], coords[1]);
}
});
}
function mapCoordinates(lat, long) {
$(".container").mapael({
map : {
name : "world_countries", // name of JS file
},
plots: {
'Random': {
latitude: lat,
longitude: long
}
}
});
}
function mapIt() {
getCountry();
}
mapIt();