TheGeomGeoJSON
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.
Requirements
- PostgreSQL >=9
- PostGIS 2.0.0 with support for JSON-C >= 0.9 compiled in
- ActiveRecord >=4
- if it exists, column the_geommust be WGS 84 SRID 4326
- if it exists, column the_geom_webmercatormust be spherical mercator SRID 3857 (which is basically identical and should be used in preference to Google webmercator unofficial SRID 900913).
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
endThen:
[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)
endCorporate support
Known issues
- It's hard to install PostGIS with JSON-C support on Mac OS X
- The the_geom_geojsongetter is rather inefficient - it's assumed you'll mostly use the setter
Contributing
- Fork it ( https://github.com/seamusabshere/the_geom_geojson/fork )
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin my-new-feature)
- Create a new Pull Request
Copyright
Copyright 2014 Faraday