[GIS] How to convert JavaScript array into geoJSON data

geojsonjavascriptjqueryleaflet

I want to upload txt, xls and csv files into leaflet. Firstly I am trying it for txt files. Js reads my txt as a js array. Now that I want to convert my js array into geoJSON. But I am confused here. I need some clue about which way should I follow.

$(function () {
        document.getElementById('file').onchange = function () {
            debugger;
            var file = this.files[0];
            var reader = new FileReader();
            reader.onload = function (progressEvent) {
                // Entire file
                console.log(this.result);
                // By lines
                var lines = this.result.split('\n');
                var list = [];
                for (var line = 0; line < lines.length; line++) {
                    list.push(lines[line]);
                }
            };
            reader.readAsText(file);
        };
    });

Best Answer

GeoJSON is not a specific object format (in terms of programing language). It is a data format specification. It is kind of a restriction to JSON for GIS data. GeoJSON data is in fact JSON with limited accepted field names and structure.

A nice aspect of Javascript is that it can read a JSON string and make an strict equivalent Object with same field structure.

If your data string is already in GeoJSON, you can give it to most Leaflet functions.

If you want to produce GeoJSON, just start like that :

var myGeoJSON = {};
myGeoJSON.type = "FeatureCollection";
myGeoJSON.features = [];
// etc...

and continue producing something that respects GeoJSON specification.