2017-04-19 19 views
-1

GeoJSONファイル(ポイントタイプ)を解析し、.CSVファイルに座標(緯度/経度)を保存します。どのようにRubyでこれを行うには?以下はGeoJSONファイルです。前もって感謝します!GeoJSONをRubyで解析し、座標を.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ファイルでの緯度とLNG貯蔵する場合は、

$ 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ファイルの内容

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

あなたもidを保存したい場合は、あなたがCOORDS

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

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

内容、ヘッダを書きたい場合、私は私の問題を解決し

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

を変更GeoJSONをCSVに変換するオンラインツールを使用します。しかし、多くのGeoJSONファイルがあると、あなたのアプローチは非常に便利になります。ありがとう! – Jason

関連する問題