Ruby GeoJSON to KML



我有一个Sinatra应用程序,我是post ing GeoJSON(多边形)..我正在寻找一个gem/脚本将JSON转换为KML,在我发送电子邮件(使用邮件gem)之前。

我能找到的最接近的东西是georuby,它似乎还没有这样的转换,肯定有办法…??或者也许这是手动实现的更好:?

刚接触Ruby (来自Python/JavaScript背景),所以感谢您的逐步学习!

Edit:对于我来说,仅仅("手动")转换坐标并插入模板kml erb/string更容易。

(我找不到将KML转换为GeoJSON的纯ruby库,要么…?)

如果ogr2ogr二进制文件在您的系统中可用,并且您可以写入tmp目录:

require 'tmpdir'
require 'fileutils'
tmpdir = Dir.mktmpdir
geojson_path = File.join(tmpdir, 'a.geojson') # the input
kml_path = File.join(tmpdir, 'a.kml') # the output
File.open(geojson_path, 'w') do |f|
  # params[:geojson] is from the web request
  f.write params[:geojson]
end
Kernel.system 'ogr2ogr', '-f', 'KML', kml_path, geojson_path
# now you can email kml
kml = File.read(kml_path)
FileUtils.rm_rf tmpdir

您可以使用名为FFI-OGR的新gem来完成此操作。

FFI,即外部函数接口,允许Ruby调用用其他语言编写的函数,而无需编写本地代码。FFI-OGR在Ruby中封装了OGR的C实现。

gem 'ffi-ogr', git: 'https://github.com/scooterw/ffi-ogr'添加到Gemfile并运行bundle install。然后,在进行转换的任何脚本中,都可以这样写:

require 'ffi-ogr'
# read in GeoJSON
geojson = OGR.read 'path/to/file.geojson'
# output as KML, write to file
geojson.to_kml 'destination/of/file.kml'

GeoRuby是相当新的,工具还没有构建得很好。然而,@scooterw正在领导一些Ruby工具的开发,这些工具可以完成基本的功能。

查看FOSS4G 2014的示例,并加入Github上的GeoRubyists组。

最新更新