I'm creating a Javascript app (without third-party frameworks or libraries) that needs to get a list of locations from a JSON object and display only those locations in a given radius. I've figured out how to determine whether or not a location's coordinates are in the desired radius, but I can't figure out how to filter the object using those results. Here's the relevant code:
function filterObj(obj) {
var radiusSize = 100;
return function filter() {
var result;
for (var i in obj) {
var lat = 41.8781;
var lon = 87.6298;
var coordinates = (obj[i].location.[0].coordinates).split(",");
lat2 = Number(coordinates[0]);
lon2 = Number(coordinates[1]);
result = toRadius(getDistance(lat, lon, lat2, lon2)) <= radiusSize;
}
return result;
};
}
function getObj() {
var xml = new XMLHttpRequest();
xml.onreadystatechange = function() {
if (xml.readyState === XMLHttpRequest.DONE) {
if (xml.readyState === 4 && xml.status === 200) {
obj = JSON.parse(xml.responseText);
var ObjFilter = filterObj(obj);
var filtered = obj.filter(objFilter);
displayLocations(filtered);
} else {
//code to handle errors
}
}
};
xml.open("GET", "/api/locations.json", true);
xml.send(null);
}
Right now, I know that filterObj() is repeatedly returning "false" for "result" because of the for loop. I've tried to store the results of filterObj() as an array, but then "result" returns several arrays containing the results of "toRadius(getDistance())", and again I know this is because of the for loop, but moving the "result" assignment out of the loop causes every result to be "false," which is incorrect.
So, how can I use the results that "toRadius(getDistance())" generates in "filterObj()" to filter the object I fetch in "getObj()" before I pass that object to "displayLocations()"?
Here's a sample of the object I'm working with:
[
{
"id": 12,
"name": "Mount Helena City Park",
"location": [
{
"city": "Helena, MT",
"address": "Mount Helena City Park \nHelena, MT 59601",
"coordinates": "46.5889179,-112.0593352"
}
]
}
]
lat, lon, lat2, lon2coming from ? As your code is now, they are undefined.JSON.parse(xml.responseText)is what you expect, thengetObjis not relevant here