TheGeomGeoJSON

Build Status

For PostGIS/PostgreSQL and ActiveRecord, provides the_geom_geojson getter and setter that update the_geom geometry(Geometry,4326) and the_geom_webmercator geometry(Geometry,3857) columns.

Web mapping libraries like Leaflet often don't support PostGIS's native Well-Known Binary (WKB) and Well-Known Text (WKT) representation, but they do support GeoJSON, so this library helps translate between the two.

ComposiciĆ³n constructiva 16

Requirements

Why the_geom and the_geom_webmercator?

Per the commonly used CartoDB column naming convention, you have a table like:

CREATE TABLE pets (
  id                    serial primary key,
  the_geom              geometry(Geometry,4326),
  the_geom_webmercator  geometry(Geometry,3857)
)

Usage with ActiveRecord

You simply include it in your models:

class Pet < ActiveRecord::Base
  include TheGeomGeoJSON::ActiveRecord
end

Then:

[1] > jerry = Pet.create!
SQL (1.0ms)  INSERT INTO "pets" DEFAULT VALUES RETURNING "id"
=> #<Pet id: 1, the_geom: nil, the_geom_webmercator: nil>

[2] > jerry.the_geom_geojson = '{"type":"Point","coordinates":[-72.4861,44.1853]}'
=> "{\"type\":\"Point\",\"coordinates\":[-72.4861,44.1853]}"

[3] > jerry.save!
SQL (1.5ms)  UPDATE "pets" SET the_geom = ST_SetSRID(ST_GeomFromGeoJSON('{"type":"Point","coordinates":[-72.4861,44.1853]}'), 4326), the_geom_webmercator = ST_Transform(ST_SetSRID(ST_GeomFromGeoJSON('{"type":"Point","coordinates":[-72.4861,44.1853]}'), 4326), 3857) WHERE id = 1
Pet Load (0.3ms)  SELECT  "pets".* FROM "pets"  WHERE "pets"."id" = $1 LIMIT 1  [["id", 1]]
=> true

[4] > jerry.the_geom
=> "0101000020E61000007AA52C431C1F52C072F90FE9B7174640"

[5] > jerry.the_geom_webmercator
=> "0101000020110F0000303776EFFEC75EC11E1648AD64F55441"

If you see warnings like:

unknown OID 136825: failed to recognize type of 'the_geom'. It will be treated as String.

... then define the OID by creating config/initializers/active_record_postgis:

ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.tap do |klass|
  klass::OID.register_type('geometry', klass::OID::Identity.new)
end

Corporate support

Faraday logo

Known issues

  1. It's hard to install PostGIS with JSON-C support on Mac OS X
  2. The the_geom_geojson getter is rather inefficient - it's assumed you'll mostly use the setter

Contributing

  1. Fork it ( https://github.com/seamusabshere/the_geom_geojson/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Copyright 2014 Faraday