【问题标题】:activerecord-postgis-adapter: Encode WKTactiverecord-postgis-adapter:编码 WKT
【发布时间】:2017-09-08 10:27:40
【问题描述】:

使用 activerecord-postgis-adapter,如何在数据库查询结果中解析/编码 wkt?

我有一个简单的地方模型:

class CreatePlaces < ActiveRecord::Migration[5.1]
 def change

  create_table :places do |t|
    t.string :name
    t.st_point :coords, :geographic => true

    t.timestamps
  end

  change_table :places do |t|
    t.index :coords, using: :gist
  end

 end
end

我通过以下方式获得所有地方:

class PlacesController < ApplicationController

 def index
   @places = Place.all

   render json: @places.to_json
 end

end

但我的 JSON 响应包含 WKT:

[
  {
      "id": 1,
      "name": "test name 1",
      "coords": "POINT (50.324192 19.037805)",
      "created_at": "2017-09-07T20:29:19.203Z",
      "updated_at": "2017-09-07T20:29:19.203Z"
  }
]

我可以像这样映射@places 和编码坐标:

class PlacesController < ApplicationController

  def index
    @places = Place.all

    @places.map { |k,v| k.coords = RGeo::GeoJSON.encode(k.coords, json_parser: :json) }

    render json: @places.to_json
  end

end

然后我得到了我想要的 - GeoJSON 形式的编码/解析坐标:

[
  {
      "id": 1,
      "name": "test name 1",
      "coords": {
          "type": "Point",
          "coordinates": [
              50.324192,
              19.037805
          ]
      },
      "created_at": "2017-09-07T20:29:19.203Z",
      "updated_at": "2017-09-07T20:29:19.203Z"
  }
]

POINT 的编码方式是否正确?

【问题讨论】:

    标签: ruby-on-rails activerecord postgis geojson


    【解决方案1】:

    将此代码添加到您的初始化程序之一:

    RGeo::ActiveRecord::GeometryMixin.set_json_generator(:geojson)
    

    https://stackoverflow.com/a/6221804

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-13
      • 1970-01-01
      • 2018-02-01
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多