]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
1b9ca05b558659a1e038f8b123554fc3e1201a46
[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     if @query.match(/^\d{5}(-\d{4})?$/)
11       @results.push search_us_postcode(@query)
12     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)
13       @results.push search_uk_postcode(@query)
14     elsif @query.match(/[A-Z]\d[A-Z]\s*\d[A-Z]\d/i)
15       @results.push search_ca_postcode(@query)
16     else
17       @results.push search_osm_namefinder(@query)
18       @results.push search_geonames(@query)
19     end
20   end
21
22 private
23
24   def search_us_postcode(query)
25     results = Array.new
26
27     # ask geocoder.us (they have a non-commercial use api)
28     response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{URI.escape(query)}")
29
30     # parse the response
31     unless response.match(/couldn't find this zip/)
32       data = response.split(/\s*,\s+/) # lat,long,town,state,zip
33       results.push({:lat => data[0], :lon => data[1], :zoom => 12,
34                     :prefix => "#{data[2]}, #{data[3]}, ",
35                     :name => data[4]})
36     end
37
38     return { :source => "Geocoder.us", :url => "http://geocoder.us/", :results => results }
39   rescue Exception => ex
40     return { :source => "Geocoder.us", :url => "http://geocoder.us/", :error => "Error contacting rpc.geocoder.us: #{ex.to_s}" }
41   end
42
43   def search_uk_postcode(query)
44     results = Array.new
45
46     # ask npemap.org.uk to do a combined npemap + freethepostcode search
47     response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{URI.escape(query)}")
48
49     # parse the response
50     unless response.match(/Error/)
51       dataline = response.split(/\n/)[1]
52       data = dataline.split(/,/) # easting,northing,postcode,lat,long
53       results.push({:lat => data[3], :lon => data[4], :zoom => 12,
54                     :name => data[2].gsub(/'/, "")})
55     end
56
57     return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :results => results }
58   rescue Exception => ex
59     return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :error => "Error contacting www.npemap.org.uk: #{ex.to_s}" }
60   end
61
62   def search_ca_postcode(query)
63     results = Array.new
64
65     # ask geocoder.ca (note - they have a per-day limit)
66     response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{URI.escape(query)}")
67
68     # parse the response
69     unless response.get_elements("geodata/error")
70       results.push({:lat => response.get_text("geodata/latt").to_s,
71                     :lon => response.get_text("geodata/longt").to_s,
72                     :zoom => 12,
73                     :name => query.upcase})
74     end
75
76     return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :results => results }
77   rescue Exception => ex
78     return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :error => "Error contacting geocoder.ca: #{ex.to_s}" }
79   end
80
81   def search_osm_namefinder(query)
82     results = Array.new
83
84     # ask OSM namefinder
85     response = fetch_xml("http://www.frankieandshadow.com/osm/search.xml?find=#{URI.escape(query)}")
86
87     # parse the response
88     response.elements.each("searchresults/named") do |named|
89       lat = named.attributes["lat"].to_s
90       lon = named.attributes["lon"].to_s
91       zoom = named.attributes["zoom"].to_s
92       place = named.elements["place/named"] || named.elements["nearestplaces/named"]
93       type = named.attributes["info"].to_s.capitalize
94       name = named.attributes["name"].to_s
95       description = named.elements["description"].to_s
96       if place
97         distance = format_distance(place.attributes["approxdistance"].to_i)
98         direction = format_direction(place.attributes["direction"].to_i)
99         placename = place.attributes["name"].to_s
100         results.push({:lat => lat, :lon => lon, :zoom => zoom,
101                       :prefix => "#{type} ", :name => name,
102                       :suffix => ", #{distance} #{direction} of #{placename}",
103                       :description => description})
104       else
105         results.push({:lat => lat, :lon => lon, :zoom => zoom,
106                       :prefix => "#{type} ", :name => name,
107                       :description => description})
108       end
109     end
110
111     return { :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :results => results }
112   rescue Exception => ex
113     return { :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :error => "Error contacting www.frankieandshadow.com: #{ex.to_s}" }
114   end
115
116   def search_geonames(query)
117     results = Array.new
118
119     # ask geonames.org
120     response = fetch_xml("http://ws.geonames.org/search?q=#{URI.escape(query)}&maxRows=20")
121
122     # parse the response
123     response.elements.each("geonames/geoname") do |geoname|
124       lat = geoname.get_text("lat").to_s
125       lon = geoname.get_text("lng").to_s
126       name = geoname.get_text("name").to_s
127       country = geoname.get_text("countryName").to_s
128       results.push({:lat => lat, :lon => lon, :zoom => 12,
129                     :name => name,
130                     :suffix => ", #{country}"})
131     end
132
133     return { :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
134   rescue Exception => ex
135     return { :source => "GeoNames", :url => "http://www.geonames.org/", :error => "Error contacting ws.geonames.org: #{ex.to_s}" }
136   end
137
138   def fetch_text(url)
139     return Net::HTTP.get(URI.parse(url))
140   end
141
142   def fetch_xml(url)
143     return REXML::Document.new(fetch_text(url))
144   end
145
146   def format_distance(distance)
147     return "less than 1km" if distance == 0
148     return "about #{distance}km"
149   end
150
151   def format_direction(bearing)
152     return "south-west" if bearing >= 22.5 and bearing < 67.5
153     return "south" if bearing >= 67.5 and bearing < 112.5
154     return "south-east" if bearing >= 112.5 and bearing < 157.5
155     return "east" if bearing >= 157.5 and bearing < 202.5
156     return "north-east" if bearing >= 202.5 and bearing < 247.5
157     return "north" if bearing >= 247.5 and bearing < 292.5
158     return "north-west" if bearing >= 292.5 and bearing < 337.5
159     return "west"
160   end
161 end