Utilize data from an API to populate GeoJSON coordinates

Trying to create a GeoJSON list using data from an API. Extracted location details like name, latitude, and longitude from the API and stored them in arrays. However, when trying to populate the GeoJSON geometry coordinates with the array values, the console is showing them as undefined. How can I successfully transfer the API values into the GeoJSON format?

https://i.sstatic.net/nPEQp.png

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>

Answer №1

After reviewing your code, I noticed a few improvements that could be made. One suggestion is to consolidate the storing and getting operations within the get method instead of directly calling push on the array element. Here is a revised version:

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) {
    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); 
    console.log(loclat); 
    console.log(loclong); 

    for (i in locname) {
      apiGeo.features.push({
        "type": "Feature",
        "geometry": {
          "type": "Point",
          "coordinates": [loclong[i], loclat[i]]
        }
      });
    }
    console.log(apiGeo); 
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you provide me with the valid JSON format for placing a new order using the Bitfinex

I've been struggling with the Bitfinex REST API, specifically the private Endpoint for placing new orders, for a few days now. While I was able to successfully send requests to other parts of the API such as Account Info or Key Info, I kept encounter ...

What is the method for modifying the parent reusable component's style from its child component?

I'm facing an issue with a reusable component in my current project. I need to modify the style of this reusable component, but I can't seem to figure out how to override the parent component's style within my child component. Parent reusab ...

Switching between various styles for rows, including grouping multiple rows together in sets

Currently, I am working on a project using Ruby programming language. Let's consider the given 2D array below: list = [ ["T1", "Cat 1"], ["T2", "Cat 2"], ["T3", "Cat 3"], ["T4", "Cat 4"], ["T5", "Cat 1"], ["T6", "Cat 2"], ["T7", "Cat 3 ...

Generating React components dynamically can bring flexibility and efficiency to the

Looking for a solution to dynamically render different components based on the arguments passed with data. While using regular or React.createElement(Item) works fine, all other options seem to fail. http://jsfiddle.net/zeen/fmhhtk5o/1/ var React = windo ...

Contrast between reactivex.io's rxjs class ES6 Observable and the Observable class found on rxjs.dev's API index

As I dive into learning RxJS, I stumbled upon two distinct definitions of Observable: https://reactivex.io/rxjs/class/es6/Observable.js~Observable.html https://rxjs.dev/api/index/class/Observable Which one holds the true definition? ...

Incorrect implementation of Bootstrap CSS in Jade template

Currently, I am leveraging Express to construct a website. However, there seems to be an issue with my jade template not displaying the bootstrap grid system accurately. Despite double-checking that my app path is correctly set through app.use(express.stat ...

Exploring Typescript: Obtaining the type of a nested optional property within an interface

I am facing an issue with the following code snippet: Property 'id' does not exist on type '{ id: string } | undefined.' as group is optional. Despite that, I need to access the type of id. How can I achieve this? interface list{ grou ...

The Next JS build process exclusively creates server-side pages

I have noticed that some of my pages like /contact, /about, and /rules are server-side generated even though I am not using getServerSideProps(). Since these pages only contain static images and text without any API requests, I want them to be treated as s ...

Converting Pandas dataframe objects to JSON and adding them to the JSON data

I am currently working on a project that involves reading an xlsx file using pandas and converting it to a JSON file. I need assistance with creating an 'if' statement to compare each row's elements with the previous line and appending them ...

Checking the efficiency of Graphql API

Currently, I am in the process of optimizing key features within my Node.js API which incorporates GraphQL. This API serves as a proxy, receiving requests from various sources and forwarding them to multiple APIs based on the request. I am interested in ...

Having trouble locating a module in Angular2 and SystemJS while constructing a module loader

What's the Situation Here? Currently, I'm immersed in a project that involves SystemJS, Angular2, and @ngrx/store. My current focus is on developing a basic module loader. Here's how it works: I create a "module" in its own folder, named ...

Issues persist with AngularJS integration using Modernizr

Incorporating AngularJS and Modernizr, I aim to identify media queries and trigger a function whenever the window or viewport is resized. My goal is to control element visibility based on whether the user is on a desktop or mobile device - certain elements ...

Securing URL Query Parameters

Working with Liferay 5.2 and ExtJS 3.4 poses a challenge for parameter passing in the URL. The issue arises when reports are generated based on parameters passed in the URL, allowing manual changes that lead to the generation of unauthorized reports. The ...

How can a button be linked directly to a particular list item?

I currently have a HTML tag within my React application that looks something like this: <ul> <li> Item 1 <button> Delete </button> </li> <li> Item 2 <button> ...

Error: Unspecified process.env property when using dotenv and node.js

I'm encountering an issue with the dotenv package. Here's the structure of my application folder: |_app_folder |_app.js |_password.env |_package.json Even though I have installed dotenv, the process.env variables are always u ...

Mysterious AngularJS

I am currently working on minimizing and obfuscating my Angular code, however I have run into a complication. I came across the "Note on minification" page at http://docs.angularjs.org/tutorial/step_05 which has been helpful, but I'm defining my contr ...

Purge ajax result upon completion of server operation

I'm currently working with an AJAX code that takes input from a radio form. The server code, upon satisfying a specific if() condition, redirects to another page on my site, such as dashboard.php! However, upon redirection, I am still seeing the rad ...

Refreshing a textarea manually in Typescript

My textarea has the CSS property height: auto;. However, I noticed that when I reset the variable associated with the [ngModel] of this textarea (e.g. using this.myNgModelVar = "";), the height of the textarea doesn't automatically decrease unless the ...

To maintain simplicity in my Swift code, I utilize a universal CodingKeys structure to streamline the manipulation of objects

When looking at a simplified example, I come across these two JSON strings: let jsonStringBird = """ { "identifier": "0001ABX", "name": "Doroty", "species_name": "Gorrion&quo ...

Discovered an issue with AngularJS involving ng-show and ng-if?

Upon my investigation, I have identified multiple issues with angularjs: <div ng-show="['[]']">this should be displayed but it is not working as expected</div> <div ng-show="[]">this should be displayed but it is not working as ...