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