简体   繁体   English

如何将javascript数组转换为geojson数据?

[英]How to convert javascript array into geojson data?

I want to upload txt, xls and csv files into leaflet. 我想将txt,xls和csv文件上传到传单中。 Firstly I am trying it for txt files. 首先,我正在尝试将其用于txt文件。 Js reads my txt as a js array. Js将我的txt读取为js数组。 Now that I want to convert my js array into geojson. 现在,我想将我的js数组转换为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... 根据给定github链接上的映射,我想您可以按照给定情况执行以下操作,但是对于一般方法,如果使用该github geoJSON库,或者如果您喜欢冒险,则可以尝试扩展以下内容,这显然更好码...

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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