]> git.openstreetmap.org Git - rails.git/blob - app/controllers/searches_controller.rb
Limit number of directions endpoint geocoding results to 1
[rails.git] / app / controllers / searches_controller.rb
1 class SearchesController < ApplicationController
2   include NominatimMethods
3
4   before_action :authorize_web
5   before_action :set_locale
6   before_action :require_oauth
7
8   authorize_resource :class => false
9
10   before_action :normalize_params
11
12   def show
13     @sources = []
14
15     if params[:lat] && params[:lon]
16       @sources.push(:name => "latlon", :url => root_path,
17                     :fetch_url => search_latlon_query_path(params.permit(:lat, :lon, :latlon_digits, :zoom)))
18       @sources.push(:name => "nominatim_reverse", :url => nominatim_reverse_query_url(:format => "html"),
19                     :fetch_url => search_nominatim_reverse_query_path(params.permit(:lat, :lon, :zoom)))
20     elsif params[:query]
21       @sources.push(:name => "nominatim", :url => nominatim_query_url(:format => "html"),
22                     :fetch_url => search_nominatim_query_path(params.permit(:query, :minlat, :minlon, :maxlat, :maxlon)))
23     end
24
25     if @sources.empty?
26       head :bad_request
27     else
28       render :layout => map_layout
29     end
30   end
31
32   private
33
34   def normalize_params
35     if (query = params[:query])
36       query.strip!
37
38       if (latlon = query.match(/^(?<ns>[NS])\s*#{dms_regexp('ns')}\W*(?<ew>[EW])\s*#{dms_regexp('ew')}$/) ||
39                    query.match(/^#{dms_regexp('ns')}\s*(?<ns>[NS])\W*#{dms_regexp('ew')}\s*(?<ew>[EW])$/))
40         params.merge!(to_decdeg(latlon.named_captures.compact)).delete(:query)
41
42       elsif (latlon = query.match(%r{^(?<lat>[+-]?\d+(?:\.\d+)?)(?:\s+|\s*[,/]\s*)(?<lon>[+-]?\d+(?:\.\d+)?)$}))
43         params.merge!(latlon.named_captures).delete(:query)
44
45         params[:latlon_digits] = true
46       end
47     end
48   end
49
50   def dms_regexp(name_prefix)
51     /
52       (?: (?<#{name_prefix}d>\d{1,3}(?:\.\d+)?)°? ) |
53       (?: (?<#{name_prefix}d>\d{1,3})°?\s*(?<#{name_prefix}m>\d{1,2}(?:\.\d+)?)['′]? ) |
54       (?: (?<#{name_prefix}d>\d{1,3})°?\s*(?<#{name_prefix}m>\d{1,2})['′]?\s*(?<#{name_prefix}s>\d{1,2}(?:\.\d+)?)["″]? )
55     /x
56   end
57
58   def to_decdeg(captures)
59     ns = captures.fetch("ns").casecmp?("s") ? -1 : 1
60     nsd = BigDecimal(captures.fetch("nsd", "0"))
61     nsm = BigDecimal(captures.fetch("nsm", "0"))
62     nss = BigDecimal(captures.fetch("nss", "0"))
63
64     ew = captures.fetch("ew").casecmp?("w") ? -1 : 1
65     ewd = BigDecimal(captures.fetch("ewd", "0"))
66     ewm = BigDecimal(captures.fetch("ewm", "0"))
67     ews = BigDecimal(captures.fetch("ews", "0"))
68
69     lat = ns * (nsd + (nsm / 60) + (nss / 3600))
70     lon = ew * (ewd + (ewm / 60) + (ews / 3600))
71
72     { :lat => lat.round(6).to_s("F"), :lon => lon.round(6).to_s("F") }
73   end
74 end