]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
Create latlon search query resource
[rails.git] / app / controllers / geocoder_controller.rb
1 class GeocoderController < ApplicationController
2   require "uri"
3   require "rexml/document"
4   include NominatimMethods
5
6   before_action :authorize_web
7   before_action :set_locale
8   before_action :require_oauth, :only => [:search]
9
10   authorize_resource :class => false
11
12   before_action :normalize_params, :only => [:search]
13
14   def search
15     @sources = []
16
17     if params[:lat] && params[:lon]
18       @sources.push(:name => "latlon", :url => root_path,
19                     :fetch_url => search_latlon_query_path(params.permit(:lat, :lon, :latlon_digits, :zoom)))
20       @sources.push(:name => "osm_nominatim_reverse", :url => nominatim_reverse_query_url(:format => "html"),
21                     :fetch_url => url_for(params.permit(:lat, :lon, :zoom).merge(:action => "search_osm_nominatim_reverse")))
22     elsif params[:query]
23       @sources.push(:name => "osm_nominatim", :url => nominatim_query_url(:format => "html"),
24                     :fetch_url => url_for(params.permit(:query, :minlat, :minlon, :maxlat, :maxlon).merge(:action => "search_osm_nominatim")))
25     end
26
27     if @sources.empty?
28       head :bad_request
29     else
30       render :layout => map_layout
31     end
32   end
33
34   def search_osm_nominatim
35     # ask nominatim
36     response = fetch_xml(nominatim_query_url(:format => "xml"))
37
38     # extract the results from the response
39     results = response.elements["searchresults"]
40
41     # create result array
42     @results = []
43
44     # create parameter hash for "more results" link
45     @more_params = params
46                    .permit(:query, :minlon, :minlat, :maxlon, :maxlat, :exclude)
47                    .merge(:exclude => results.attributes["exclude_place_ids"])
48
49     # parse the response
50     results.elements.each("place") do |place|
51       lat = place.attributes["lat"]
52       lon = place.attributes["lon"]
53       klass = place.attributes["class"]
54       type = place.attributes["type"]
55       name = place.attributes["display_name"]
56       min_lat, max_lat, min_lon, max_lon = place.attributes["boundingbox"].split(",")
57       prefix_name = if type.empty?
58                       ""
59                     else
60                       t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.tr("_", " ").capitalize
61                     end
62       if klass == "boundary" && type == "administrative"
63         rank = (place.attributes["address_rank"].to_i + 1) / 2
64         prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
65         border_type = nil
66         place_type = nil
67         place_tags = %w[linked_place place]
68         place.elements["extratags"].elements.each("tag") do |extratag|
69           border_type = t "geocoder.search_osm_nominatim.border_types.#{extratag.attributes['value']}", :default => border_type if extratag.attributes["key"] == "border_type"
70           place_type = t "geocoder.search_osm_nominatim.prefix.place.#{extratag.attributes['value']}", :default => place_type if place_tags.include?(extratag.attributes["key"])
71         end
72         prefix_name = place_type || border_type || prefix_name
73       end
74       prefix = t ".prefix_format", :name => prefix_name
75       object_type = place.attributes["osm_type"]
76       object_id = place.attributes["osm_id"]
77
78       @results.push(:lat => lat, :lon => lon,
79                     :min_lat => min_lat, :max_lat => max_lat,
80                     :min_lon => min_lon, :max_lon => max_lon,
81                     :prefix => prefix, :name => name,
82                     :type => object_type, :id => object_id)
83     end
84
85     render "searches/queries/create"
86   rescue StandardError => e
87     host = URI(Settings.nominatim_url).host
88     @error = "Error contacting #{host}: #{e}"
89     render "searches/queries/error"
90   end
91
92   def search_osm_nominatim_reverse
93     # get query parameters
94     zoom = params[:zoom]
95
96     # create result array
97     @results = []
98
99     # ask nominatim
100     response = fetch_xml(nominatim_reverse_query_url(:format => "xml"))
101
102     # parse the response
103     response.elements.each("reversegeocode/result") do |result|
104       lat = result.attributes["lat"]
105       lon = result.attributes["lon"]
106       object_type = result.attributes["osm_type"]
107       object_id = result.attributes["osm_id"]
108       description = result.text
109
110       @results.push(:lat => lat, :lon => lon,
111                     :zoom => zoom,
112                     :name => description,
113                     :type => object_type, :id => object_id)
114     end
115
116     render "searches/queries/create"
117   rescue StandardError => e
118     host = URI(Settings.nominatim_url).host
119     @error = "Error contacting #{host}: #{e}"
120     render "searches/queries/error"
121   end
122
123   private
124
125   def fetch_text(url)
126     response = OSM.http_client.get(URI.parse(url))
127
128     if response.success?
129       response.body
130     else
131       raise response.status.to_s
132     end
133   end
134
135   def fetch_xml(url)
136     REXML::Document.new(fetch_text(url))
137   end
138
139   def normalize_params
140     if (query = params[:query])
141       query.strip!
142
143       if (latlon = query.match(/^(?<ns>[NS])\s*#{dms_regexp('ns')}\W*(?<ew>[EW])\s*#{dms_regexp('ew')}$/) ||
144                    query.match(/^#{dms_regexp('ns')}\s*(?<ns>[NS])\W*#{dms_regexp('ew')}\s*(?<ew>[EW])$/))
145         params.merge!(to_decdeg(latlon.named_captures.compact)).delete(:query)
146
147       elsif (latlon = query.match(%r{^(?<lat>[+-]?\d+(?:\.\d+)?)(?:\s+|\s*[,/]\s*)(?<lon>[+-]?\d+(?:\.\d+)?)$}))
148         params.merge!(latlon.named_captures).delete(:query)
149
150         params[:latlon_digits] = true
151       end
152     end
153   end
154
155   def dms_regexp(name_prefix)
156     /
157       (?: (?<#{name_prefix}d>\d{1,3}(?:\.\d+)?)°? ) |
158       (?: (?<#{name_prefix}d>\d{1,3})°?\s*(?<#{name_prefix}m>\d{1,2}(?:\.\d+)?)['′]? ) |
159       (?: (?<#{name_prefix}d>\d{1,3})°?\s*(?<#{name_prefix}m>\d{1,2})['′]?\s*(?<#{name_prefix}s>\d{1,2}(?:\.\d+)?)["″]? )
160     /x
161   end
162
163   def to_decdeg(captures)
164     ns = captures.fetch("ns").casecmp?("s") ? -1 : 1
165     nsd = BigDecimal(captures.fetch("nsd", "0"))
166     nsm = BigDecimal(captures.fetch("nsm", "0"))
167     nss = BigDecimal(captures.fetch("nss", "0"))
168
169     ew = captures.fetch("ew").casecmp?("w") ? -1 : 1
170     ewd = BigDecimal(captures.fetch("ewd", "0"))
171     ewm = BigDecimal(captures.fetch("ewm", "0"))
172     ews = BigDecimal(captures.fetch("ews", "0"))
173
174     lat = ns * (nsd + (nsm / 60) + (nss / 3600))
175     lon = ew * (ewd + (ewm / 60) + (ews / 3600))
176
177     { :lat => lat.round(6).to_s("F"), :lon => lon.round(6).to_s("F") }
178   end
179 end