Skip to content

Instantly share code, notes, and snippets.

@nathanl
Last active May 27, 2019 06:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanl/97df524aea27b82fcccc to your computer and use it in GitHub Desktop.
Save nathanl/97df524aea27b82fcccc to your computer and use it in GitHub Desktop.
Rails code to use PostGIS in place of some of Geocoder's functionality - based on http://ngauthier.com/2013/08/postgis-and-rails-a-simple-approach.html
# Scopes that make use of the index
def self.within_distance_of(lat:, lng:, meters:)
where(%{
ST_DWithin(
ST_GeographyFromText(
'SRID=4326;POINT(' || #{table_name}.longitude || ' ' || #{table_name}.latitude || ')'
),
ST_GeographyFromText('SRID=4326;POINT(%f %f)'),
%d
)
} % [lng, lat, meters])
end
def self.ordered_by_distance_from(lat:, lng:)
order(
%{
ST_Distance(
ST_GeographyFromText(
'SRID=4326;POINT(' || #{table_name}.longitude || ' ' || #{table_name}.latitude || ')'
),
ST_GeographyFromText('SRID=4326;POINT(%f %f)')
)
} % [lng, lat]
)
end
# Migration to create index that allows us to query as if we had geography
# columns, even though we don't because Rails doesn't play nicely with those
# see http://ngauthier.com/2013/08/postgis-and-rails-a-simple-approach.html
class AddGeoQueryIndexToCmsStation < ActiveRecord::Migration
def up
execute %{
create index index_cms_stations_on_geography_point ON cms_stations using gist (
ST_GeographyFromText(
'SRID=4326;POINT(' || cms_stations.longitude || ' ' || cms_stations.latitude || ')'
)
)
}
end
def down
execute %{drop index index_cms_stations_on_geography_point}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment