简体   繁体   中英

How to convert javascript array into geojson data?

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 confused here. Need some clue about how kind a way should I follow. I appreciate your time and thank you for your kind replies.

  $(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); }; }); 

According to the mapping at the given github link I guess you may do as i show below for the given case however for a general approach it is obviously better if you use that github geoJSON library or if you are adventurous you may try to extend the following code...

 var dataStr = "name: 'Location A', category: 'Store', street: 'Market', lat: 39.984, lng: -75.343, name: 'Location B', category: 'House', street: 'Broad', lat: 39.284, lng: -75.833, name: 'Location C', category: 'Office', street: 'South', lat: 39.123, lng: -74.534", data = dataStr.split(/\\s*,\\s*(?=name)/g) .map(function(d){ return d.split(/\\s*,\\s*/) .reduce(function(r,s){ var [k,v] = s.replace(/\\s*'|'\\s*$/g,"") .split(":"); return k === "name" || k === "category" ? (r.properties[k] = v, r) : k === "lat" || k === "lng" ? (r.geometry.coordinates.unshift(+v), r) : r; }, {type : "feature", geometry : {type : "Point", coordinates: [] }, properties: {name : "", category: "" } }); }), geoJSON = { type : "FeatureCollection", features: data }; console.log(geoJSON); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM