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