通过API填充GeoJSON坐标

时间:2019-07-01 05:05:06

标签: javascript arrays json api geojson

我需要通过API创建一个GeoJSON列表。我从API中提取了位置的名称,纬度和经度,并将其放入数组中。然后,我尝试从数组中填充GeoJSON几何坐标,但控制台将坐标显示为未定义。如何从API获取值到GeoJSON列表?

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>

1 个答案:

答案 0 :(得分:0)

您的代码进行了许多更正,我将存储和获取操作放入get方法中,直接在array元素上调用push就足够了。请考虑以下内容:

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>