# 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
Slide 21
Slide 21 text
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
Slide 22
Slide 22 text
class Location < ActiveRecord::Base
GEOFACTORY =
RGeo::Geographic.spherical_factory(srid: 4326)
set_rgeo_factory_for_column :coords, GEOFACTORY
end
Slide 23
Slide 23 text
Points in radius
Slide 24
Slide 24 text
point = Location::GEOFACTORY.point(27, 53)
radius = 50_000 # 50 km
Location.where('st_dwithin(coords, ?, ?)', point, radius)
.order('st_distance(coords, ?)', point)
Slide 25
Slide 25 text
Squeel
• https://github.com/ernie/squeel
Slide 26
Slide 26 text
point = Location::GEOFACTORY.point(27, 53)
radius = 50_000 # 50 km
Location.where { st_dwithin(coords, point, radius) }
.order { st_distance(coords, point) }
Slide 27
Slide 27 text
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) }
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
Slide 39
Slide 39 text
class TimeZonePolygon < ActiveRecord::Base
set_rgeo_factory_for_column :geometry,
RGeo::Geographic.spherical_factory(srid: 4326)
end
Slide 40
Slide 40 text
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