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