2017-04-19 303 views
-1

我想解析一个GeoJSON文件(点类型)并将坐标(纬度/经度)保存到.CSV文件。如何用Ruby做到这一点?以下是一个GeoJSON文件。提前致谢!如何使用Ruby解析GeoJSON并将坐标保存为.csv文件?

{ "type": "FeatureCollection", 
    "features": [ 
{ "type": "Feature", 
    "id": 1, 
    "properties": { 
    "cluster": { 
     "x": -0.229559, 
     "y": 0.270089 
    } 
    }, 
    "geometry": { 
    "type": "Point", 
    "coordinates": [ 
     -74.1518294, 
     40.5793043 
    ] 
    } 
}, 
{ 
    "type": "Feature", 
    "id": 2, 
    "properties": { 
    "cluster": { 
     "x": 0.00379515, 
     "y": 0.121912 
    } 
    }, 
    "geometry": { 
    "type": "Point", 
    "coordinates": [ 
     -74.0818064, 
     40.9278118 
    ] 
    } 
}, ]}   

回答

0

您可以使用rgeo-geojson gem做到这一点:

require 'rgeo/geo_json' 
require 'csv' 

points = RGeo::GeoJSON.decode(json, json_parser: :json) # json must be a string here 

CSV.open("points.csv", "w") do |csv| 
    csv << ["x", "y"] 
    points.each do |point| 
    csv << [point.geometry.x, point.geometry.y] 
    end 
end 
0

如果你只是想存储纬度和经度的csv文件,

$ cat geo.json 
{ "type": "FeatureCollection", 
    "features": [ 
{ 
    "type": "Feature", 
    "id": 1, 
    "properties": { 
    "cluster": { 
     "x": -0.229559, 
     "y": 0.270089 
    } 
    }, 
    "geometry": { 
    "type": "Point", 
    "coordinates": [ 
     -74.1518294, 
     40.5793043 
    ] 
    } 
}, 
{ 
    "type": "Feature", 
    "id": 2, 
    "properties": { 
    "cluster": { 
     "x": 0.00379515, 
     "y": 0.121912 
    } 
    }, 
    "geometry": { 
    "type": "Point", 
    "coordinates": [ 
     -74.0818064, 
     40.9278118 
    ] 
    } 
} 
] 
    } 

Ruby脚本

require 'json' 
require 'csv' 

q = h['features'].map {|e| e['geometry']['coordinates'] } 
#=> [[-74.1518294, 40.5793043], [-74.0818064, 40.9278118]] 
CSV.open('coords.csv', 'wb') {|csv| q.each {|e|csv << e }} 

csv文件的内容。 COORDS的

$ cat coords.csv 
-74.1518294,40.5793043 
-74.0818064,40.9278118 

如果你也想存储的ID,改变

q = h["features"].map {|e| [e['id'], e['geometry']['coordinates']].flatten } 

,如果你想要写头,

CSV.open('coords.csv', "wb") do |csv| 
    csv << ['ID', 'LAT', 'LNG'] 
    q.each {|e|csv << e } 
end 

内容

$ cat coords.csv 
ID,LAT,LNG 
1,-74.1518294,40.5793043 
2,-74.0818064,40.9278118 
+0

我解决我的问题通过使用将GeoJSON转换为CSV的在线工具。但是当我有很多GeoJSON文件时,你的方法会非常方便。谢谢! – Jason

相关问题