4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
# File 'app/controllers/open_places/autocomplete_controller.rb', line 4
def index
query_string = (params[:q] || params[:like] || params[:contains] || params[:starts] || params[:ends] || nil)
raise "A query param (q, like, contains, starts or ends) or location (near, e.g. 42.0-120.0) is requered" unless query_string.present?
op = (params.keys & ['q', 'like', 'contains', 'starts', 'ends']).flatten.shift
@results = OpenPlaces::Geo
@results = @results.where(geotype: params[:type].split(",").map{|t| "OpenPlaces::#{t}" }) if params[:type].present?
@results = @results.autocomplete(query_string, op) if query_string.present?
@results = @results.near(params[:near]) if params[:near].present?
@results = @results.order('scalerank ASC')
@results = @results.limit(params[:limit])
if @results.empty?
OpenPlaces::Geo.transaction do
@result = OpenPlaces::Geo.create(long_name: query_string)
if @result.id.present?
@results = OpenPlaces::Geo.where(id: @result.id)
else
@results = OpenPlaces::Geo.where(slug: @result.slug)
end
end
end
respond_to do |format|
format.json do
render json: @results.to_json(except: OpenPlaces::Geo.GEO_FIELDS), root: false, status: 200, :callback => params['callback']
end
format.geojson do
render text: @results.to_geojson('latlng').first["geojson"], status: 200, :callback => params['callback']
end
end
rescue ActionController::UnknownFormat => e
render json: @results.to_json(except: 'geom'), root: false, status: 200, :callback => params['callback']
rescue => e
render json: { error: e.message }, status: 400, :callback => params['callback']
end
|