]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
Add B000FTFT (as well as B000FTF) to the list of layers we should
[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 :set_locale
7
8   def search
9     query = params[:query]
10     results = Array.new
11
12     query.sub(/^\s+/, "")
13     query.sub(/\s+$/, "")
14
15     if query.match(/^[+-]?\d+(\.\d*)?\s*[\s,]\s*[+-]?\d+(\.\d*)?$/)
16       results.push search_latlon(query)
17     elsif query.match(/^\d{5}(-\d{4})?$/)
18       results.push search_us_postcode(query)
19     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)
20       results.push search_uk_postcode(query)
21       results.push search_osm_namefinder(query)
22     elsif query.match(/^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i)
23       results.push search_ca_postcode(query)
24     else
25       results.push search_osm_namefinder(query)
26       results.push search_geonames(query)
27     end
28
29     results_count = count_results(results)
30
31     render :update do |page|
32       page.replace_html :sidebar_content, :partial => 'results', :object => results
33
34       if results_count == 1
35         position = results.collect { |s| s[:results] }.compact.flatten[0]
36         page.call "setPosition", position[:lat].to_f, position[:lon].to_f, position[:zoom].to_i
37       else
38         page.call "openSidebar"
39       end
40     end
41   end
42   
43   def description
44     results = Array.new
45
46     lat = params[:lat]
47     lon = params[:lon]
48
49     results.push description_osm_namefinder("cities", lat, lon, 2)
50     results.push description_osm_namefinder("towns", lat, lon, 4)
51     results.push description_osm_namefinder("places", lat, lon, 10)
52     results.push description_geonames(lat, lon)
53
54     render :update do |page|
55       page.replace_html :sidebar_content, :partial => 'results', :object => results
56       page.call "openSidebar"
57     end
58   end
59
60 private
61
62   def search_latlon(query)
63     results = Array.new
64
65     # decode the location
66     if m = query.match(/^([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)$/)
67       lat = m[1].to_f
68       lon = m[3].to_f
69     end
70
71     # generate results
72     if lat < -90 or lat > 90
73       return { :source => "Internal", :url => "http://openstreetmap.org/", :error => "Latitude #{lat} out of range" }
74     elsif lon < -180 or lon > 180
75       return { :source => "Internal", :url => "http://openstreetmap.org/", :error => "Longitude #{lon} out of range" }
76     else
77       results.push({:lat => lat, :lon => lon,
78                     :zoom => APP_CONFIG['postcode_zoom'],
79                     :name => "#{lat}, #{lon}"})
80
81       return { :source => "Internal", :url => "http://openstreetmap.org/", :results => results }
82     end
83   end
84
85   def search_us_postcode(query)
86     results = Array.new
87
88     # ask geocoder.us (they have a non-commercial use api)
89     response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
90
91     # parse the response
92     unless response.match(/couldn't find this zip/)
93       data = response.split(/\s*,\s+/) # lat,long,town,state,zip
94       results.push({:lat => data[0], :lon => data[1],
95                     :zoom => APP_CONFIG['postcode_zoom'],
96                     :prefix => "#{data[2]}, #{data[3]}, ",
97                     :name => data[4]})
98     end
99
100     return { :source => "Geocoder.us", :url => "http://geocoder.us/", :results => results }
101   rescue Exception => ex
102     return { :source => "Geocoder.us", :url => "http://geocoder.us/", :error => "Error contacting rpc.geocoder.us: #{ex.to_s}" }
103   end
104
105   def search_uk_postcode(query)
106     results = Array.new
107
108     # ask npemap.org.uk to do a combined npemap + freethepostcode search
109     response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
110
111     # parse the response
112     unless response.match(/Error/)
113       dataline = response.split(/\n/)[1]
114       data = dataline.split(/,/) # easting,northing,postcode,lat,long
115       postcode = data[2].gsub(/'/, "")
116       zoom = APP_CONFIG['postcode_zoom'] - postcode.count("#")
117       results.push({:lat => data[3], :lon => data[4], :zoom => zoom,
118                     :name => postcode})
119     end
120
121     return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :results => results }
122   rescue Exception => ex
123     return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :error => "Error contacting www.npemap.org.uk: #{ex.to_s}" }
124   end
125
126   def search_ca_postcode(query)
127     results = Array.new
128
129     # ask geocoder.ca (note - they have a per-day limit)
130     response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
131
132     # parse the response
133     if response.get_elements("geodata/error").empty?
134       results.push({:lat => response.get_text("geodata/latt").to_s,
135                     :lon => response.get_text("geodata/longt").to_s,
136                     :zoom => APP_CONFIG['postcode_zoom'],
137                     :name => query.upcase})
138     end
139
140     return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :results => results }
141   rescue Exception => ex
142     return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :error => "Error contacting geocoder.ca: #{ex.to_s}" }
143   end
144
145   def search_osm_namefinder(query)
146     results = Array.new
147
148     # ask OSM namefinder
149     response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{escape_query(query)}")
150
151     # parse the response
152     response.elements.each("searchresults/named") do |named|
153       lat = named.attributes["lat"].to_s
154       lon = named.attributes["lon"].to_s
155       zoom = named.attributes["zoom"].to_s
156       place = named.elements["place/named"] || named.elements["nearestplaces/named"]
157       type = named.attributes["info"].to_s.capitalize
158       name = named.attributes["name"].to_s
159       description = named.elements["description"].to_s
160
161       if name.empty?
162         prefix = ""
163         name = type
164       else
165         prefix = "#{type} "
166       end
167
168       if place
169         distance = format_distance(place.attributes["approxdistance"].to_i)
170         direction = format_direction(place.attributes["direction"].to_i)
171         placename = format_name(place.attributes["name"].to_s)
172         suffix = ", #{distance} #{direction} of #{placename}"
173
174         if place.attributes["rank"].to_i <= 30
175           parent = nil
176           parentrank = 0
177           parentscore = 0
178
179           place.elements.each("nearestplaces/named") do |nearest|
180             nearestrank = nearest.attributes["rank"].to_i
181             nearestscore = nearestrank / nearest.attributes["distance"].to_f
182
183             if nearestrank > 30 and
184                ( nearestscore > parentscore or
185                  ( nearestscore == parentscore and nearestrank > parentrank ) )
186               parent = nearest
187               parentrank = nearestrank
188               parentscore = nearestscore
189             end
190           end
191
192           if parent
193             parentname = format_name(parent.attributes["name"].to_s)
194
195             if  place.attributes["info"].to_s == "suburb"
196               suffix = "#{suffix}, #{parentname}"
197             else
198               parentdistance = format_distance(parent.attributes["approxdistance"].to_i)
199               parentdirection = format_direction(parent.attributes["direction"].to_i)
200               suffix = "#{suffix} (#{parentdistance} #{parentdirection} of #{parentname})"
201             end
202           end
203         end
204       else
205         suffix = ""
206       end
207
208       results.push({:lat => lat, :lon => lon, :zoom => zoom,
209                     :prefix => prefix, :name => name, :suffix => suffix,
210                     :description => description})
211     end
212
213     return { :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :results => results }
214   rescue Exception => ex
215     return { :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :error => "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}" }
216   end
217
218   def search_geonames(query)
219     results = Array.new
220
221     # ask geonames.org
222     response = fetch_xml("http://ws.geonames.org/search?q=#{escape_query(query)}&maxRows=20")
223
224     # parse the response
225     response.elements.each("geonames/geoname") do |geoname|
226       lat = geoname.get_text("lat").to_s
227       lon = geoname.get_text("lng").to_s
228       name = geoname.get_text("name").to_s
229       country = geoname.get_text("countryName").to_s
230       results.push({:lat => lat, :lon => lon,
231                     :zoom => APP_CONFIG['geonames_zoom'],
232                     :name => name,
233                     :suffix => ", #{country}"})
234     end
235
236     return { :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
237   rescue Exception => ex
238     return { :source => "GeoNames", :url => "http://www.geonames.org/", :error => "Error contacting ws.geonames.org: #{ex.to_s}" }
239   end
240
241   def description_osm_namefinder(types, lat, lon, max)
242     results = Array.new
243
244     # ask OSM namefinder
245     response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{types}+near+#{lat},#{lon}&max=#{max}")
246
247     # parse the response
248     response.elements.each("searchresults/named") do |named|
249       lat = named.attributes["lat"].to_s
250       lon = named.attributes["lon"].to_s
251       zoom = named.attributes["zoom"].to_s
252       place = named.elements["place/named"] || named.elements["nearestplaces/named"]
253       type = named.attributes["info"].to_s
254       name = named.attributes["name"].to_s
255       description = named.elements["description"].to_s
256       distance = format_distance(place.attributes["approxdistance"].to_i)
257       direction = format_direction((place.attributes["direction"].to_i - 180) % 360)
258       prefix = "#{distance} #{direction} of #{type} "
259       results.push({:lat => lat, :lon => lon, :zoom => zoom,
260                     :prefix => prefix.capitalize, :name => name,
261                     :description => description})
262     end
263
264     return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :results => results }
265   rescue Exception => ex
266     return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :error => "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}" }
267   end
268
269   def description_geonames(lat, lon)
270     results = Array.new
271
272     # ask geonames.org
273     response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
274
275     # parse the response
276     response.elements.each("geonames/countrySubdivision") do |geoname|
277       name = geoname.get_text("adminName1").to_s
278       country = geoname.get_text("countryName").to_s
279       results.push({:prefix => "#{name}, #{country}"})
280     end
281
282     return { :type => "Location", :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
283   rescue Exception => ex
284     return { :type => "Location", :source => "GeoNames", :url => "http://www.geonames.org/", :error => "Error contacting ws.geonames.org: #{ex.to_s}" }
285   end
286
287   def fetch_text(url)
288     return Net::HTTP.get(URI.parse(url))
289   end
290
291   def fetch_xml(url)
292     return REXML::Document.new(fetch_text(url))
293   end
294
295   def format_distance(distance)
296     return "less than 1km" if distance == 0
297     return "about #{distance}km"
298   end
299
300   def format_direction(bearing)
301     return "south-west" if bearing >= 22.5 and bearing < 67.5
302     return "south" if bearing >= 67.5 and bearing < 112.5
303     return "south-east" if bearing >= 112.5 and bearing < 157.5
304     return "east" if bearing >= 157.5 and bearing < 202.5
305     return "north-east" if bearing >= 202.5 and bearing < 247.5
306     return "north" if bearing >= 247.5 and bearing < 292.5
307     return "north-west" if bearing >= 292.5 and bearing < 337.5
308     return "west"
309   end
310
311   def format_name(name)
312     return name.gsub(/( *\[[^\]]*\])*$/, "")
313   end
314
315   def count_results(results)
316     count = 0
317
318     results.each do |source|
319       count += source[:results].length if source[:results]
320     end
321
322     return count
323   end
324
325   def escape_query(query)
326     return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
327   end
328 end