我想解析一个GeoJSON文件(Point类型)并将坐标(lat / lng)保存到.CSV文件。如何用Ruby做到这一点?以下是GeoJSON文件。提前谢谢!
{ "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 :(得分: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
答案 1 :(得分:0)
如果您只想在csv文件中存储lat和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,请更改
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
coords的内容
$ cat coords.csv
ID,LAT,LNG
1,-74.1518294,40.5793043
2,-74.0818064,40.9278118