2012-10-31 28 views
5

我有軌跡與,activerecord-postgis-adapterrgeo-geojson運行。使用MIME類型呈現爲GeoJSON(或選擇性地作爲WKT/WKB)

目前我可以使用默認的「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上工作得很好:我可以在我的控制器使用此代碼:

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

我希望有人能告訴我如何使一些特定對象,以GeoJSON的沒有設置全局JSON渲染器到:geojson。 !?

編輯:

我的物體看起來像這樣在Rails的控制檯:

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

+0

以GeoJSON是JSON和正確的介質類型是「應用程序/ JSON「。也許考慮GeoJSON數據的完全不同的觀點? – sgillies

+0

感謝您的回答:但仍然存在這樣的問題:如果沒有(!!)設置全局json_generator,我怎樣才能用GeoJSON生成JSON而不是WKT? –

回答

9

您可以使用一個工廠這樣一個特定@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... 
    } 
}