0

I need to create a GeoJSON list from an API. I extracted the location's name, latitude and longitude from the API and put it into arrays. I then try to populate the GeoJSON geometry coordinates from the arrays but console displays the coordinates as undefined. How do I get the values from the API to the GeoJSON list?

Result from console.log

locname = [];
loclat = [];
loclong = [];

var api = $.getJSON("https://api.data.gov.sg/v1/environment/rainfall?date=2019-06-21",
   function rainfall(data_rainfall){
    console.log(data_rainfall);
    var j;        
    for (j in data_rainfall.metadata.stations){
        locname[j] = data_rainfall.metadata.stations[j].name;
        loclat[j] = data_rainfall.metadata.stations[j].location.latitude;
        loclong[j] = data_rainfall.metadata.stations[j].location.longitude;
    }
    locname.push(locname[j]);
    loclat.push(loclat[j]);
    loclong.push(loclong[j]);

    return locname, loclat, loclong;
});
console.log(locname); // Values appear in console
console.log(loclat);  // values appear in console
console.log(loclong); // values appear in console

var apiGeo = {
    type: "FeatureCollection",
    features: []
};

for (i in api){
    apiGeo.features.push({
        "type":"Feature",
        "geometry":{
            "type": "Point",
            "coordinates": [loclong[i], loclat[i]]
        }

    });
}
console.log(apiGeo); // values appear as 'undefined' in console
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
shrys
  • 5,860
  • 2
  • 21
  • 36
abdillah
  • 61
  • 3

1 Answers1

0

Your code had quite a few corrections, I placed the storing and getting operations inside get method, directly calling push on the array element would suffice. Consider the following:

locname = [];
loclat = [];
loclong = [];

var apiGeo = {
  type: "FeatureCollection",
  features: []
};

var api = $.getJSON("https://api.data.gov.sg/v1/environment/rainfall?date=2019-06-21",
  function rainfall(data_rainfall) {
    //console.log(data_rainfall);
    var j;
    for (j in data_rainfall.metadata.stations) {
      locname.push(data_rainfall.metadata.stations[j].name);
      loclat.push(data_rainfall.metadata.stations[j].location.latitude);
      loclong.push(data_rainfall.metadata.stations[j].location.longitude);
    }

    console.log(locname); // Values appear in console
    console.log(loclat); // values appear in console
    console.log(loclong); // values appear in console

    for (i in locname) {
      apiGeo.features.push({
        "type": "Feature",
        "geometry": {
          "type": "Point",
          "coordinates": [loclong[i], loclat[i]]
        }

      });
    }
    console.log(apiGeo); // values appear as 'undefined' in console
    //return locname, loclat, loclong;
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
shrys
  • 5,860
  • 2
  • 21
  • 36