7

我有 RailsPostGISactiverecord-postgis-adapter运行rgeo-geojson

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

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

但是现在我想要一个自定义的 MIME-Type,所以我可以调用“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它并且工作正常:我可以在我的控制器中使用此代码:

respond_to do |format|
  format.json { render json: @object }
  format.geojson { render text: "test" }
end

我希望有人能告诉我如何在不将全局 JSON 渲染器设置为:geojson. !?

编辑:

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

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

4

1 回答 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...
    }
}
于 2013-03-23T02:09:56.607 回答