1 class GeocoderController < ApplicationController
 
   4   require 'rexml/document'
 
  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)
 
  23       results.push search_osm_namefinder(query)
 
  24       results.push search_geonames(query)
 
  27     results_count = count_results(results)
 
  29     render :update do |page|
 
  30       page.replace_html :sidebar_content, :partial => 'results', :object => results
 
  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
 
  36         page.call "openSidebar"
 
  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)
 
  52     render :update do |page|
 
  53       page.replace_html :sidebar_content, :partial => 'results', :object => results
 
  54       page.call "openSidebar"
 
  60   def search_latlon(query)
 
  64     if m = query.match(/^([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)$/)
 
  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" }
 
  75       results.push({:lat => lat, :lon => lon,
 
  76                     :zoom => APP_CONFIG['postcode_zoom'],
 
  77                     :name => "#{lat}, #{lon}"})
 
  79       return { :source => "Internal", :url => "http://openstreetmap.org/", :results => results }
 
  83   def search_us_postcode(query)
 
  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)}")
 
  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]}, ",
 
  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}" }
 
 103   def search_uk_postcode(query)
 
 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)}")
 
 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,
 
 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}" }
 
 124   def search_ca_postcode(query)
 
 127     # ask geocoder.ca (note - they have a per-day limit)
 
 128     response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
 
 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})
 
 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}" }
 
 143   def search_osm_namefinder(query)
 
 147     response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{escape_query(query)}")
 
 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
 
 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}"
 
 172         if place.attributes["rank"].to_i <= 30
 
 177           place.elements.each("nearestplaces/named") do |nearest|
 
 178             nearestrank = nearest.attributes["rank"].to_i
 
 179             nearestscore = nearestrank / nearest.attributes["distance"].to_f
 
 181             if nearestrank > 30 and
 
 182                ( nearestscore > parentscore or
 
 183                  ( nearestscore == parentscore and nearestrank > parentrank ) )
 
 185               parentrank = nearestrank
 
 186               parentscore = nearestscore
 
 191             parentname = format_name(parent.attributes["name"].to_s)
 
 193             if  place.attributes["info"].to_s == "suburb"
 
 194               suffix = "#{suffix}, #{parentname}"
 
 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})"
 
 206       results.push({:lat => lat, :lon => lon, :zoom => zoom,
 
 207                     :prefix => prefix, :name => name, :suffix => suffix,
 
 208                     :description => description})
 
 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}" }
 
 216   def search_geonames(query)
 
 220     response = fetch_xml("http://ws.geonames.org/search?q=#{escape_query(query)}&maxRows=20")
 
 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'],
 
 231                     :suffix => ", #{country}"})
 
 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}" }
 
 239   def description_osm_namefinder(types, lat, lon, max)
 
 243     response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{types}+near+#{lat},#{lon}&max=#{max}")
 
 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})
 
 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}" }
 
 267   def description_geonames(lat, lon)
 
 271     response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
 
 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}"})
 
 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}" }
 
 286     return Net::HTTP.get(URI.parse(url))
 
 290     return REXML::Document.new(fetch_text(url))
 
 293   def format_distance(distance)
 
 294     return "less than 1km" if distance == 0
 
 295     return "about #{distance}km"
 
 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
 
 309   def format_name(name)
 
 310     return name.gsub(/( *\[[^\]]*\])*$/, "")
 
 313   def count_results(results)
 
 316     results.each do |source|
 
 317       count += source[:results].length if source[:results]
 
 323   def escape_query(query)
 
 324     return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))