我有运行 PostGISactiverecord-postgis-adapterrgeo-geojson 的 Rails。

目前我可以使用默认的“object.json” URL 来获取 WKT/WKB 格式的 JSON 字符串。它看起来像这样:

{"description":null,"id":1,"position":"POINT (10.0 47.0)"}

但现在我想要一个自定义的 MIME 类型,所以我可以调用“object.geojson”来获取这样的 GeoJSON 格式:
{"description":null,"id":1,"position":{"type":"Point","coordinates": [10.0, 47.0]}}

我发现将 JSON 编码器设置为 GeoJSON 的唯一方法是使用 RGeo::ActiveRecord::GeometryMixin.set_json_generator(:geojson)RGeo::ActiveRecord::GeometryMixin.set_json_generator(:wkt) 全局设置它。 但是我只想在本地设置,可以吗?

我已经将 Mime::Type.register "application/json", :geojson, %w( text/x-json application/jsonrequest ) 添加到 mime_types.rb 并且它工作正常:我可以在我的 Controller 中使用此代码:
respond_to do |format|
  format.json { render json: @object }
  format.geojson { render text: "test" }
end

我希望有人能告诉我如何在不将全局 JSON 渲染器设置为 :geojson 的情况下将某些特定对象渲染到 GeoJSON。 !?

编辑:

我的对象在 Rails 控制台中如下所示:
#<Anchor id: 1, description: nil, position: #<RGeo::Geos::CAPIPointImpl:0x3fc93970aac0 "POINT (10.0 47.0)">>

最佳答案

您可以将这样的工厂用于特定的 @object

factory = RGeo::GeoJSON::EntityFactory.instance

feature = factory.feature(@object.position, nil, { desc: @object.description})

并对其进行编码:
RGeo::GeoJSON.encode feature

它应该输出如下内容:
{
  "type" => "Feature",
  "geometry" => {
    "type" => "Point",
    "coordinates"=>[1.0, 1.0]
  },
  "properties" => {
    "description" => "something"
  }
}

或一组功能:
RGeo::GeoJSON.encode factory.feature_collection(features)

给予:
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      # the rest of the feature...
    },
    {
      "type": "Feature",
      # another feature...
    }
}

关于ruby-on-rails - 使用MIME类型呈现为GeoJSON(或选择性地呈现为WKT/WKB),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13155815/

10-11 22:09
查看更多