使用MIME类型将内容渲染为GeoJSON(或选择性地作为WKT / WKB)

7

我使用了Rails框架,其中包含PostGIS, activerecord-postgis-adapterrgeo-geojson

目前我可以使用默认的“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_types.rb中添加了Mime::Type.register "application/json", :geojson, %w( text/x-json application/jsonrequest ),它运行良好:我可以在控制器中使用此代码:
respond_to do |format|
  format.json { render json: @object }
  format.geojson { render text: "test" }
end

我希望有人能告诉我如何将某些特定对象呈现为GeoJSON,而不必设置全局JSON渲染器为:geojson。 !?

编辑:

在Rails Console中,我的对象看起来像这样:

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


GeoJSON是JSON格式,其媒体类型为“application/json”。也许考虑一种完全不同的视图来展示GeoJSON数据? - sgillies
谢谢你的回答:但是还有一个问题:我如何在不设置全局json_generator的情况下使用GeoJSON生成JSON而不是WKT? - Benjamin M
1个回答

11

您可以像这样使用一个工厂来为特定的@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...
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接