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