Last active
May 27, 2019 06:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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