]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
Ajaxify message deletion
[rails.git] / app / controllers / geocoder_controller.rb
1 class GeocoderController < ApplicationController
2   require 'uri'
3   require 'net/http'
4   require 'rexml/document'
5
6   before_filter :authorize_web
7   before_filter :set_locale
8
9   def search
10     @query = params[:query]
11     @sources = Array.new
12
13     @query.sub(/^\s+/, "")
14     @query.sub(/\s+$/, "")
15
16     if @query.match(/^[+-]?\d+(\.\d*)?\s*[\s,]\s*[+-]?\d+(\.\d*)?$/)
17       @sources.push "latlon"
18     elsif @query.match(/^\d{5}(-\d{4})?$/)
19       @sources.push "us_postcode"
20       @sources.push "osm_nominatim"
21     elsif @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 @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   end
32
33   def search_latlon
34     # get query parameters
35     query = params[:query]
36
37     # create result array
38     @results = Array.new
39
40     # decode the location
41     if m = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
42       lat = m[1].to_f
43       lon = m[3].to_f
44     end
45
46     # generate results
47     if lat < -90 or lat > 90
48       @error = "Latitude #{lat} out of range"
49       render :action => "error"
50     elsif lon < -180 or lon > 180
51       @error = "Longitude #{lon} out of range"
52       render :action => "error"
53     else
54       @results.push({:lat => lat, :lon => lon,
55                      :zoom => POSTCODE_ZOOM,
56                      :name => "#{lat}, #{lon}"})
57
58       render :action => "results"
59     end
60   end
61
62   def search_us_postcode
63     # get query parameters
64     query = params[:query]
65
66     # create result array
67     @results = Array.new
68
69     # ask geocoder.us (they have a non-commercial use api)
70     response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
71
72     # parse the response
73     unless response.match(/couldn't find this zip/)
74       data = response.split(/\s*,\s+/) # lat,long,town,state,zip
75       @results.push({:lat => data[0], :lon => data[1],
76                      :zoom => POSTCODE_ZOOM,
77                      :prefix => "#{data[2]}, #{data[3]},",
78                      :name => data[4]})
79     end
80
81     render :action => "results"
82   rescue Exception => ex
83     @error = "Error contacting rpc.geocoder.us: #{ex.to_s}"
84     render :action => "error"
85   end
86
87   def search_uk_postcode
88     # get query parameters
89     query = params[:query]
90
91     # create result array
92     @results = Array.new
93
94     # ask npemap.org.uk to do a combined npemap + freethepostcode search
95     response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
96
97     # parse the response
98     unless response.match(/Error/)
99       dataline = response.split(/\n/)[1]
100       data = dataline.split(/,/) # easting,northing,postcode,lat,long
101       postcode = data[2].gsub(/'/, "")
102       zoom = POSTCODE_ZOOM - postcode.count("#")
103       @results.push({:lat => data[3], :lon => data[4], :zoom => zoom,
104                      :name => postcode})
105     end
106
107     render :action => "results"
108   rescue Exception => ex
109     @error = "Error contacting www.npemap.org.uk: #{ex.to_s}"
110     render :action => "error"
111   end
112
113   def search_ca_postcode
114     # get query parameters
115     query = params[:query]
116     @results = Array.new
117
118     # ask geocoder.ca (note - they have a per-day limit)
119     response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
120
121     # parse the response
122     if response.get_elements("geodata/error").empty?
123       @results.push({:lat => response.get_text("geodata/latt").to_s,
124                      :lon => response.get_text("geodata/longt").to_s,
125                      :zoom => POSTCODE_ZOOM,
126                      :name => query.upcase})
127     end
128
129     render :action => "results"
130   rescue Exception => ex
131     @error = "Error contacting geocoder.ca: #{ex.to_s}"
132     render :action => "error"
133   end
134
135   def search_osm_nominatim
136     # get query parameters
137     query = params[:query]
138     minlon = params[:minlon]
139     minlat = params[:minlat]
140     maxlon = params[:maxlon]
141     maxlat = params[:maxlat]
142
143     # get view box
144     if minlon && minlat && maxlon && maxlat
145       viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
146     end
147
148     # get objects to excude
149     if params[:exclude]
150       exclude = "&exclude_place_ids=#{params[:exclude].join(',')}"
151     end
152
153     # ask nominatim
154     response = fetch_xml("#{NOMINATIM_URL}search?format=xml&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{request.user_preferred_languages.join(',')}")
155
156     # create result array
157     @results = Array.new
158
159     # create parameter hash for "more results" link
160     @more_params = params.reverse_merge({ :exclude => [] })
161
162     # extract the results from the response
163     results =  response.elements["searchresults"]
164
165     # parse the response
166     results.elements.each("place") do |place|
167       lat = place.attributes["lat"].to_s
168       lon = place.attributes["lon"].to_s
169       klass = place.attributes["class"].to_s
170       type = place.attributes["type"].to_s
171       name = place.attributes["display_name"].to_s
172       min_lat,max_lat,min_lon,max_lon = place.attributes["boundingbox"].to_s.split(",")
173       prefix_name = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
174       prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
175
176       @results.push({:lat => lat, :lon => lon,
177                      :min_lat => min_lat, :max_lat => max_lat,
178                      :min_lon => min_lon, :max_lon => max_lon,
179                      :prefix => prefix, :name => name})
180       @more_params[:exclude].push(place.attributes["place_id"].to_s)
181     end
182
183     render :action => "results"
184 #  rescue Exception => ex
185 #    @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
186 #    render :action => "error"
187   end
188
189   def search_geonames
190     # get query parameters
191     query = params[:query]
192
193     # create result array
194     @results = Array.new
195
196     # ask geonames.org
197     response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&maxRows=20&username=#{GEONAMES_USERNAME}")
198
199     # parse the response
200     response.elements.each("geonames/geoname") do |geoname|
201       lat = geoname.get_text("lat").to_s
202       lon = geoname.get_text("lng").to_s
203       name = geoname.get_text("name").to_s
204       country = geoname.get_text("countryName").to_s
205       @results.push({:lat => lat, :lon => lon,
206                      :zoom => GEONAMES_ZOOM,
207                      :name => name,
208                      :suffix => ", #{country}"})
209     end
210
211     render :action => "results"
212   rescue Exception => ex
213     @error = "Error contacting ws.geonames.org: #{ex.to_s}"
214     render :action => "error"
215   end
216
217   def description
218     @sources = Array.new
219
220     @sources.push({ :name => "osm_nominatim" })
221     @sources.push({ :name => "geonames" })
222   end
223
224   def description_osm_nominatim
225     # get query parameters
226     lat = params[:lat]
227     lon = params[:lon]
228     zoom = params[:zoom]
229
230     # create result array
231     @results = Array.new
232
233     # ask nominatim
234     response = fetch_xml("#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{request.user_preferred_languages.join(',')}")
235
236     # parse the response
237     response.elements.each("reversegeocode/result") do |result|
238       description = result.get_text.to_s
239
240       @results.push({:prefix => "#{description}"})
241     end
242
243     render :action => "results"
244   rescue Exception => ex
245     @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
246     render :action => "error"
247   end
248
249   def description_geonames
250     # get query parameters
251     lat = params[:lat]
252     lon = params[:lon]
253
254     # create result array
255     @results = Array.new
256
257     # ask geonames.org
258     response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
259
260     # parse the response
261     response.elements.each("geonames/countrySubdivision") do |geoname|
262       name = geoname.get_text("adminName1").to_s
263       country = geoname.get_text("countryName").to_s
264       @results.push({:prefix => "#{name}, #{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 end