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