What is the best way to transform a JSON document collection into a GeoJSON FeatureCollection?

Using my RESTapi, I extract data from a mongoDB and pass it to my mapbox gl app as a JSON array with the help of the following code:

$.ajax(
            {
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: myUrl,
                cache: false,
                async: true,
                timeout: 5000,
                dataType: "json",
                success: function (data)
                {
                    console.log("Reading Data");
                    console.log(data);
                },
                error: function (xhr, ajaxOptions, thrownError)
                {
                    console.log("http Status Response: " + xhr.status);
                    console.log(thrownError);
                }
            });

The data is structured as individual documents in mongoDB, and a GET request retrieves it in the following format.

[
        {
            "_id": "588a3d5a524da321dd937891",
            "__v": 0,
            "geometry": {
                "type": "Point",
                "coordinates": [ -113.5299938027191, 53.42859997065679 ]
            },
            "type": "Feature",
            "properties": {
                "icon": "horse-riding-15",
                "title": "A Horse",
                "description": "A Horse description",
                "date": "2017-01-26T18:18:02.175Z"
            }
        },
        {
            "_id": "588ac68aa99e6a38134997b5",
            "__v": 0,
            "geometry": {
                "type": "Point",
                "coordinates": [ -113.56076949999999, 53.4528447 ]
            },
            "type": "Feature",
            "properties": {
                "icon": "dog-park-15",
                "title": "A Dog",
                "description": "A Dog description",
                "date": "2017-01-27T04:03:22.381Z"
            }
        }
]

To display this data in mapbox, it needs to be a part of a GeoJSON Feature Collection, which should be structured like this (including the type info at the start, and {} wrapper):

{
    "type": "FeatureCollection",
    "features":     [
            {
                "_id": "588a3d5a524da321dd937891",
                "__v": 0,
                "geometry": {
                    "type": "Point",
                    "coordinates": [ -113.5299938027191, 53.42859997065679 ]
                },
                "type": "Feature",
                "properties": {
                    "icon": "horse-riding-15",
                    "title": "A Horse",
                    "description": "A Horse description",
                    "date": "2017-01-26T18:18:02.175Z"
                }
            },
            {
                "_id": "588ac68aa99e6a38134997b5",
                "__v": 0,
                "geometry": {
                    "type": "Point",
                    "coordinates": [ -113.56076949999999, 53.4528447 ]
                },
                "type": "Feature",
                "properties": {
                    "icon": "dog-park-15",
                    "title": "A Dog",
                    "description": "A Dog description",
                    "date": "2017-01-27T04:03:22.381Z"
                }
            }
    ]
}

I'm not sure if there's a preferred method for this conversion, a technique I'm overlooking, or some client-side code that can automatically reformat and add the extra data after downloading. At this point, I'm uncertain about the best approach to include the extra wrapper data.

Answer №1

To achieve the desired output, you can generate your own object. The following example could assist you in this process.

var dataGenerated = [
        {
            "_id": "588a3d5a524da321dd937891",
            "__v": 0,
            "geometry": {
                "type": "Point",
                "coordinates": [ -113.5299938027191, 53.42859997065679 ]
            },
            "type": "Feature",
            "properties": {
                "icon": "horse-riding-15",
                "title": "A Horse",
                "description": "A Horse description",
                "date": "2017-01-26T18:18:02.175Z"
            }
        },
        {
            "_id": "588ac68aa99e6a38134997b5",
            "__v": 0,
            "geometry": {
                "type": "Point",
                "coordinates": [ -113.56076949999999, 53.4528447 ]
            },
            "type": "Feature",
            "properties": {
                "icon": "dog-park-15",
                "title": "A Dog",
                "description": "A Dog description",
                "date": "2017-01-27T04:03:22.381Z"
            }
        }
];


var geoData = {};

geoData["type"] = "FeatureCollection";
geoData["features"] = dataGenerated;


console.log(JSON.stringify(geoData));

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

The rotation function of a THREE.js object seems to be malfunctioning

Currently, I am facing an issue with a Blender object that I have successfully displayed on my web page using THREE.js. However, for some reason the object is not rotating when my loop function is called. In my approach to working with JavaScript, I am tr ...

Generating a one-of-a-kind json structure using pandas

I am currently working with a dataset that looks like this Year type Median_Home_Value 786252 2010 analyzed 11973.000 786253 2011 analyzed 12500.000 786254 2012 analyzed 13325.000 786255 2013 analyzed 14204.000 ...

Exploring the values of subarrays in MongoDB

After converting my XML data to JSON, the formatting looks a little odd, but here's the basic structure I'm dealing with: { "World": { "Continents": { "Continent": [ "Asia", "Europe", "Africa" ] } ...

javascript, contrasting functions and variables

As I delve into the world of Javascript and JQuery (hence why I chose the example below), I have observed an interesting behavior. I noticed that not only can I define a function and call it, but I can also just do something else mysterious by using the do ...

What is a way to adjust the width of fixed columns in a Bootstrap 4.0 responsive table?

I've been struggling to make this work despite following similar questions and answers. I attempted to adjust the column width by directly setting each one, but nothing seems to change! <thead style="white-space: nowrap"> ...

Error: JSONResponse is missing a semicolon before the statement in the syntax

I encountered the following error: SyntaxError: missing ; before statement Although I am unsure of what is causing this error, here is the code snippet that I am currently working with: (function pollschedule(){ $.ajax({type: "GET", dataType: "j ...

Unusual conduct when employing basic directive for validation messages

Within my code, I have implemented the following directive: App.directive("validateMsgFor", function(){ return{ templateUrl : "view/templates/validateMsgFor.html", restrict: "E", scope: { field : "=" } ...

Incorrectly Scheduled Events in FullCalendar

While using FullCalendar to display dates, I noticed a discrepancy where some dates appear correctly while others do not. The issue seems to be related to events with a start time of 8pm or later. For example, on August 17th, there are two events schedule ...

Handling error reporting using JSON in jQuery AJAX post success

UPDATE: I have resolved the PHP errors mentioned in previous Answers, however, the issue still persists. I am attempting to implement an error message display in case of a failed POST request and a success message for successfully completed requests. Curr ...

Dynamically inserting templates into directives

I've been attempting to dynamically add a template within my Angular directive. Following the guidance in this answer, I utilized the link function to compile the variable into an HTML element. However, despite my efforts, I haven't been success ...

Convert the 'value' attribute in HTML into a clickable link

Is there a way to make the output value of an HTML input field into a clickable link? Right now, it appears as follows: <input type="email" class="form-control" name="contactEmail" value="<?php echo $row_rsContactD ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...

Trouble with formatting in React

I am presented with the following code snippet that I did not author: render: function () { if(this.state.loading){ return <div><span><i className="fa fa-spinner fa-spin"></i> Loading...</span></div& ...

Troubleshooting the Issue of Angular Model Not Refreshing in Angular.js

Running into an issue with my directive where the model isn't updating as expected. Here's a snippet of my HTML code: <div class="text-area-container"> <textarea ng-model="chatText" ng-keyup="updateCount(chatText)">< ...

Utilize React Hook Form to easily reset the value of an MUI Select component

I created a dropdown menu where users can select from "Item 1", "Item 2", and "Item 3". Additionally, there is a "Reset" button that allows users to clear their selection and make a new one. Below is the code I used: import React from ...

Encountering problems when transforming Next.js server components into client components

I've been working on a blog site using next.js. Initially, I had a home page that was a server component, but I wanted to convert it into a client component to add interactivity like pagination. However, after converting the code to a client componen ...

Traditional method for comparing prevProps in componentDidUpdate

As I work on prototyping, I've noticed that when new props come in as an array of complex objects, prevProps.myProp===this.props.myProp always returns false. While using JSON.stringify for comparison seems to work, it doesn't feel very reliable. ...

Execution of scripts upon completion of document loading via AJAX

When loading a portion of HTML through AJAX, my expectation was that the JavaScript code inside would not run because it is dependent on the DOM being ready. However, to my surprise, the code within document.ready is still executing. I have even placed a ...

Establishing a connection between a frontend Javascript client and a backend Node.js/express server

Recently, my close friend successfully created a working client website using Javascript. Meanwhile, I have managed to get my server code up and running smoothly, extracting specific data through MySQL. We are now seeking some advice on how we can link t ...

Attempting to verify JavaScript input by utilizing OnClick and a custom function. Regardless of the content inputted, the system consistently confirms that the format is accurate

I am currently working on a project that involves an HTML file and an external JavaScript file. In the HTML file, there is user input and a validation button that triggers the courseValidation() function when clicked. However, I am facing an issue with the ...