]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
Replace searching.gif with loader from iD
[rails.git] / app / controllers / geocoder_controller.rb
1 # coding: utf-8
2
3 class GeocoderController < ApplicationController
4   require 'uri'
5   require 'net/http'
6   require 'rexml/document'
7
8   before_filter :authorize_web
9   before_filter :set_locale
10
11   def search
12     normalize_params
13
14     @sources = []
15     if params[:lat] && params[:lon]
16       @sources.push "osm_nominatim_reverse"
17       @sources.push "geonames_reverse"
18     elsif params[:query].match(/^\d{5}(-\d{4})?$/)
19       @sources.push "us_postcode"
20       @sources.push "osm_nominatim"
21     elsif params[:query].match(/^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\s*[0-9][ABD-HJLNP-UW-Z]{2})$/i)
22       @sources.push "uk_postcode"
23       @sources.push "osm_nominatim"
24     elsif params[:query].match(/^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i)
25       @sources.push "ca_postcode"
26       @sources.push "osm_nominatim"
27     else
28       @sources.push "osm_nominatim"
29       @sources.push "geonames" if defined?(GEONAMES_USERNAME)
30     end
31
32     render :layout => map_layout
33   end
34
35   def search_us_postcode
36     # get query parameters
37     query = params[:query]
38
39     # create result array
40     @results = Array.new
41
42     # ask geocoder.us (they have a non-commercial use api)
43     response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
44
45     # parse the response
46     unless response.match(/couldn't find this zip/)
47       data = response.split(/\s*,\s+/) # lat,long,town,state,zip
48       @results.push({:lat => data[0], :lon => data[1],
49                      :zoom => POSTCODE_ZOOM,
50                      :prefix => "#{data[2]}, #{data[3]},",
51                      :name => data[4]})
52     end
53
54     render :action => "results"
55   rescue Exception => ex
56     @error = "Error contacting rpc.geocoder.us: #{ex.to_s}"
57     render :action => "error"
58   end
59
60   def search_uk_postcode
61     # get query parameters
62     query = params[:query]
63
64     # create result array
65     @results = Array.new
66
67     # ask npemap.org.uk to do a combined npemap + freethepostcode search
68     response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
69
70     # parse the response
71     unless response.match(/Error/)
72       dataline = response.split(/\n/)[1]
73       data = dataline.split(/,/) # easting,northing,postcode,lat,long
74       postcode = data[2].gsub(/'/, "")
75       zoom = POSTCODE_ZOOM - postcode.count("#")
76       @results.push({:lat => data[3], :lon => data[4], :zoom => zoom,
77                      :name => postcode})
78     end
79
80     render :action => "results"
81   rescue Exception => ex
82     @error = "Error contacting www.npemap.org.uk: #{ex.to_s}"
83     render :action => "error"
84   end
85
86   def search_ca_postcode
87     # get query parameters
88     query = params[:query]
89     @results = Array.new
90
91     # ask geocoder.ca (note - they have a per-day limit)
92     response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
93
94     # parse the response
95     if response.get_elements("geodata/error").empty?
96       @results.push({:lat => response.get_text("geodata/latt").to_s,
97                      :lon => response.get_text("geodata/longt").to_s,
98                      :zoom => POSTCODE_ZOOM,
99                      :name => query.upcase})
100     end
101
102     render :action => "results"
103   rescue Exception => ex
104     @error = "Error contacting geocoder.ca: #{ex.to_s}"
105     render :action => "error"
106   end
107
108   def search_osm_nominatim
109     # get query parameters
110     query = params[:query]
111     minlon = params[:minlon]
112     minlat = params[:minlat]
113     maxlon = params[:maxlon]
114     maxlat = params[:maxlat]
115
116     # get view box
117     if minlon && minlat && maxlon && maxlat
118       viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
119     end
120
121     # get objects to excude
122     if params[:exclude]
123       exclude = "&exclude_place_ids=#{params[:exclude].join(',')}"
124     end
125
126     # ask nominatim
127     response = fetch_xml("#{NOMINATIM_URL}search?format=xml&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
128
129     # create result array
130     @results = Array.new
131
132     # create parameter hash for "more results" link
133     @more_params = params.reverse_merge({ :exclude => [] })
134
135     # extract the results from the response
136     results =  response.elements["searchresults"]
137
138     # parse the response
139     results.elements.each("place") do |place|
140       lat = place.attributes["lat"].to_s
141       lon = place.attributes["lon"].to_s
142       klass = place.attributes["class"].to_s
143       type = place.attributes["type"].to_s
144       name = place.attributes["display_name"].to_s
145       min_lat,max_lat,min_lon,max_lon = place.attributes["boundingbox"].to_s.split(",")
146       prefix_name = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
147       if klass == 'boundary' and type == 'administrative'
148         rank = (place.attributes["place_rank"].to_i + 1) / 2
149         prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
150       end
151       prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
152       object_type = place.attributes["osm_type"]
153       object_id = place.attributes["osm_id"]
154
155       @results.push({:lat => lat, :lon => lon,
156                      :min_lat => min_lat, :max_lat => max_lat,
157                      :min_lon => min_lon, :max_lon => max_lon,
158                      :prefix => prefix, :name => name,
159                      :type => object_type, :id => object_id})
160       @more_params[:exclude].push(place.attributes["place_id"].to_s)
161     end
162
163     render :action => "results"
164 #  rescue Exception => ex
165 #    @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
166 #    render :action => "error"
167   end
168
169   def search_geonames
170     # get query parameters
171     query = params[:query]
172
173     # create result array
174     @results = Array.new
175
176     # ask geonames.org
177     response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&maxRows=20&username=#{GEONAMES_USERNAME}")
178
179     # parse the response
180     response.elements.each("geonames/geoname") do |geoname|
181       lat = geoname.get_text("lat").to_s
182       lon = geoname.get_text("lng").to_s
183       name = geoname.get_text("name").to_s
184       country = geoname.get_text("countryName").to_s
185       @results.push({:lat => lat, :lon => lon,
186                      :zoom => GEONAMES_ZOOM,
187                      :name => name,
188                      :suffix => ", #{country}"})
189     end
190
191     render :action => "results"
192   rescue Exception => ex
193     @error = "Error contacting ws.geonames.org: #{ex.to_s}"
194     render :action => "error"
195   end
196
197   def search_osm_nominatim_reverse
198     # get query parameters
199     lat = params[:lat]
200     lon = params[:lon]
201     zoom = params[:zoom]
202
203     # create result array
204     @results = Array.new
205
206     # ask nominatim
207     response = fetch_xml("#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
208
209     # parse the response
210     response.elements.each("reversegeocode/result") do |result|
211       lat = result.attributes["lat"].to_s
212       lon = result.attributes["lon"].to_s
213       object_type = result.attributes["osm_type"]
214       object_id = result.attributes["osm_id"]
215       description = result.get_text.to_s
216
217       @results.push({:lat => lat, :lon => lon,
218                      :zoom => zoom,
219                      :name => description,
220                      :type => object_type, :id => object_id})
221     end
222
223     render :action => "results"
224   rescue Exception => ex
225     @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
226     render :action => "error"
227   end
228
229   def search_geonames_reverse
230     # get query parameters
231     lat = params[:lat]
232     lon = params[:lon]
233
234     # create result array
235     @results = Array.new
236
237     # ask geonames.org
238     response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
239
240     # parse the response
241     response.elements.each("geonames/countrySubdivision") do |geoname|
242       name = geoname.get_text("adminName1").to_s
243       country = geoname.get_text("countryName").to_s
244       @results.push({:lat => lat, :lon => lon,
245                      :zoom => GEONAMES_ZOOM,
246                      :name => name,
247                      :suffix => ", #{country}"})
248     end
249
250     render :action => "results"
251   rescue Exception => ex
252     @error = "Error contacting ws.geonames.org: #{ex.to_s}"
253     render :action => "error"
254   end
255
256 private
257
258   def fetch_text(url)
259     return Net::HTTP.get(URI.parse(url))
260   end
261
262   def fetch_xml(url)
263     return REXML::Document.new(fetch_text(url))
264   end
265
266   def format_distance(distance)
267     return t("geocoder.distance", :count => distance)
268   end
269
270   def format_direction(bearing)
271     return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
272     return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
273     return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
274     return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
275     return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
276     return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
277     return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
278     return t("geocoder.direction.west")
279   end
280
281   def format_name(name)
282     return name.gsub(/( *\[[^\]]*\])*$/, "")
283   end
284
285   def count_results(results)
286     count = 0
287
288     results.each do |source|
289       count += source[:results].length if source[:results]
290     end
291
292     return count
293   end
294
295   def escape_query(query)
296     return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
297   end
298
299   def normalize_params
300     query = params[:query]
301     return unless query
302
303     query.strip!
304
305     if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
306       params.merge!(nsew_to_decdeg(latlon)).delete(:query)
307     elsif latlon = query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
308       params.merge!(nsew_to_decdeg(latlon)).delete(:query)
309
310     elsif latlon = query.match(/^([NS])\s*(\d{1,3})°?\s*(\d{1,3}(\.\d*)?)?['′]?\W*([EW])\s*(\d{1,3})°?\s*(\d{1,3}(\.\d*)?)?['′]?$/).try(:captures) # [NSEW] degrees, decimal minutes
311       params.merge!(ddm_to_decdeg(latlon)).delete(:query)
312     elsif latlon = query.match(/^(\d{1,3})°?\s*(\d{1,3}(\.\d*)?)?['′]?\s*([NS])\W*(\d{1,3})°?\s*(\d{1,3}(\.\d*)?)?['′]?\s*([EW])$/).try(:captures) # degrees, decimal minutes [NSEW]
313       params.merge!(ddm_to_decdeg(latlon)).delete(:query)
314
315     elsif latlon = query.match(/^([NS])\s*(\d{1,3})°?\s*(\d{1,2})['′]?\s*(\d{1,3}(\.\d*)?)?["″]?\W*([EW])\s*(\d{1,3})°?\s*(\d{1,2})['′]?\s*(\d{1,3}(\.\d*)?)?["″]?$/).try(:captures) # [NSEW] degrees, minutes, decimal seconds
316       params.merge!(dms_to_decdeg(latlon)).delete(:query)
317     elsif latlon = query.match(/^(\d{1,3})°?\s*(\d{1,2})['′]?\s*(\d{1,3}(\.\d*)?)?["″]\s*([NS])\W*(\d{1,3})°?\s*(\d{1,2})['′]?\s*(\d{1,3}(\.\d*)?)?["″]?\s*([EW])$/).try(:captures) # degrees, minutes, decimal seconds [NSEW]
318       params.merge!(dms_to_decdeg(latlon)).delete(:query)
319
320     elsif latlon = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
321       params.merge!({:lat => latlon[1].to_f, :lon => latlon[3].to_f}).delete(:query)
322     end
323   end
324
325   def nsew_to_decdeg(captures)
326     begin
327       Float(captures[0])
328       captures[2].downcase != 's' ? lat = captures[0].to_f : lat = -(captures[0].to_f)
329       captures[5].downcase != 'w' ? lon = captures[3].to_f : lon = -(captures[3].to_f)
330     rescue
331       captures[0].downcase != 's' ? lat = captures[1].to_f : lat = -(captures[1].to_f)
332       captures[3].downcase != 'w' ? lon = captures[4].to_f : lon = -(captures[4].to_f)
333     end
334     {:lat => lat, :lon => lon}
335   end
336
337   def ddm_to_decdeg(captures)
338     begin
339       Float(captures[0])
340       captures[3].downcase != 's' ? lat = captures[0].to_f + captures[1].to_f/60 : lat = -(captures[0].to_f + captures[1].to_f/60)
341       captures[7].downcase != 'w' ? lon = captures[4].to_f + captures[5].to_f/60 : lon = -(captures[4].to_f + captures[5].to_f/60)
342     rescue
343       captures[0].downcase != 's' ? lat = captures[1].to_f + captures[2].to_f/60 : lat = -(captures[1].to_f + captures[2].to_f/60)
344       captures[4].downcase != 'w' ? lon = captures[5].to_f + captures[6].to_f/60 : lon = -(captures[5].to_f + captures[6].to_f/60)
345     end
346     {:lat => lat, :lon => lon}
347   end
348
349   def dms_to_decdeg(captures)
350     begin
351       Float(captures[0])
352       captures[4].downcase != 's' ? lat = captures[0].to_f + (captures[1].to_f + captures[2].to_f/60)/60 : lat = -(captures[0].to_f + (captures[1].to_f + captures[2].to_f/60)/60)
353       captures[9].downcase != 'w' ? lon = captures[5].to_f + (captures[6].to_f + captures[7].to_f/60)/60 : lon = -(captures[5].to_f + (captures[6].to_f + captures[7].to_f/60)/60)
354     rescue
355       captures[0].downcase != 's' ? lat = captures[1].to_f + (captures[2].to_f + captures[3].to_f/60)/60 : lat = -(captures[1].to_f + (captures[2].to_f + captures[3].to_f/60)/60)
356       captures[5].downcase != 'w' ? lon = captures[6].to_f + (captures[7].to_f + captures[8].to_f/60)/60 : lon = -(captures[6].to_f + (captures[7].to_f + captures[8].to_f/60)/60)
357     end
358     {:lat => lat, :lon => lon}
359   end
360
361 end