Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Geospatial applications on Rails

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.

Geospatial applications on Rails

Avatar for Sergey Nartimov

Sergey Nartimov

June 01, 2013
Tweet

More Decks by Sergey Nartimov

Other Decks in Programming

Transcript

  1. About • Rails, Rubinius, Elixir contributor • Software engineer at

    Brainspec Sergey Nartimov Brainspec https://github.com/lest twitter: @just_lest
  2. # config/database.yml adapter: postgis # When postgresql >= 9.1 and

    postgis >= 2.0 postgis_extension: true # When postgresql < 9.1 or postgis < 2.0 # e.g. for postgresql 9.1 and postgis 1.5 on ubuntu script_dir: "/usr/share/postgresql/9.1/contrib/postgis-1.5" schema_search_path: public,postgis
  3. create_table :locations do |t| t.point :coords, geographic: true end create_table

    :locations do |t| t.string :text t.point :coords, srid: 3785 end add_index :locations, :coords, spatial: true
  4. point = Location::GEOFACTORY.point(27, 53) radius = 50_000 # 50 km

    Location.where('st_dwithin(coords, ?, ?)', point, radius) .order('st_distance(coords, ?)', point)
  5. point = Location::GEOFACTORY.point(27, 53) radius = 50_000 # 50 km

    Location.where { st_dwithin(coords, point, radius) } .order { st_distance(coords, point) }
  6. class Location < ActiveRecord::Base GEOFACTORY = RGeo::Geographic.simple_mercator_factory set_rgeo_factory_for_column :coords, GEOFACTORY.projection_factory

    end point = Location::GEOFACTORY.point(27, 53) radius = 50_000 / Math.cos(lat * Math::PI / 180.0) Location.where { st_dwithin(coords, point, radius) } .order { st_distance(coords, point) }
  7. sw = Location::GEOFACTORY.point(48.389537, 54.306922) ne = Location::GEOFACTORY.point(48.399643, 54.311216) bbox =

    RGeo::Cartesian::BoundingBox.create_from_points(sw, ne) Location.where('coords && ?', bbox)
  8. class CreateTimeZonePolygons < ActiveRecord::Migration def change create_table :time_zone_polygons do |t|

    t.string :tzid t.geometry :geometry, geographic: true t.timestamps end add_index :time_zone_polygons, :geometry, spatial: true end end
  9. RGeo::Shapefile::Reader.open('tz_world.shp') do |file| file.each do |record| polygon = TimeZonePolygon.new polygon.tzid

    = record.attributes['TZID'] polygon.geometry = record.geometry polygon.save! end end