Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render as GeoJSON (or selectively as WKT/WKB) using MIME-Types

I have Rails with PostGIS, activerecord-postgis-adapter and rgeo-geojson running.

At the moment I can use default "object.json" URLs to get a JSON string with WKT/WKB format. It looks like this:

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

But now I want to have a custom MIME-Type, so I can call "object.geojson" to get GeoJSON format like this:

{"description":null,"id":1,"position":{"type":"Point","coordinates": [10.0, 47.0]}}

The only way I found to set the JSON-encoder to GeoJSON was to set it globally using RGeo::ActiveRecord::GeometryMixin.set_json_generator(:geojson) and RGeo::ActiveRecord::GeometryMixin.set_json_generator(:wkt). But I just want to set it locally, is this possible?

I already added Mime::Type.register "application/json", :geojson, %w( text/x-json application/jsonrequest ) to mime_types.rb and it works fine: I can use this code in my controller:

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

I hope someone can tell me how to render some specific object to GeoJSON without setting the global JSON renderer to :geojson. !?

EDIT:

My objects look like this in Rails Console:

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

like image 257
Benjamin M Avatar asked Oct 31 '12 10:10

Benjamin M


1 Answers

You can use a factory like this for a specific @object

factory = RGeo::GeoJSON::EntityFactory.instance

feature = factory.feature(@object.position, nil, { desc: @object.description})

And encode it:

RGeo::GeoJSON.encode feature

It should output something like this:

{
  "type" => "Feature",
  "geometry" => {
    "type" => "Point",
    "coordinates"=>[1.0, 1.0]
  },
  "properties" => {
    "description" => "something"
  }
}

Or a collection of features:

RGeo::GeoJSON.encode factory.feature_collection(features)

Giving:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      # the rest of the feature...
    },
    {
      "type": "Feature",
      # another feature...
    }
}
like image 185
Mauricio Pasquier Juan Avatar answered Nov 15 '22 09:11

Mauricio Pasquier Juan