使用MIME类型呈现为GeoJSON(或选择性地呈现为WKT/WKB)

Ben*_*n M 6 ruby-on-rails geojson wkt

我有Rails PostGIS,activerecord-postgis-adapter并且rgeo-geojson正在运行.

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

{"description":null,"id":1,"position":"POINT (10.0 47.0)"}
Run Code Online (Sandbox Code Playgroud)

但是现在我想要一个自定义MIME类型,所以我可以调用"object.geojson"来获取GeoJSON格式,如下所示:

{"description":null,"id":1,"position":{"type":"Point","coordinates": [10.0, 47.0]}}
Run Code Online (Sandbox Code Playgroud)

我发现将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和它的作品罚款:我可以在我的控制器使用此代码:

respond_to do |format|
  format.json { render json: @object }
  format.geojson { render text: "test" }
end
Run Code Online (Sandbox Code Playgroud)

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

编辑:

我的对象在Rails控制台中看起来像这样:

#<Anchor id: 1, description: nil, position: #<RGeo::Geos::CAPIPointImpl:0x3fc93970aac0 "POINT (10.0 47.0)">>

Mau*_*uan 11

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

factory = RGeo::GeoJSON::EntityFactory.instance

feature = factory.feature(@object.position, nil, { desc: @object.description})
Run Code Online (Sandbox Code Playgroud)

编码:

RGeo::GeoJSON.encode feature
Run Code Online (Sandbox Code Playgroud)

它应该输出这样的东西:

{
  "type" => "Feature",
  "geometry" => {
    "type" => "Point",
    "coordinates"=>[1.0, 1.0]
  },
  "properties" => {
    "description" => "something"
  }
}
Run Code Online (Sandbox Code Playgroud)

或者一系列功能:

RGeo::GeoJSON.encode factory.feature_collection(features)
Run Code Online (Sandbox Code Playgroud)

赠送:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      # the rest of the feature...
    },
    {
      "type": "Feature",
      # another feature...
    }
}
Run Code Online (Sandbox Code Playgroud)