1 # The OSM module provides support functions for OSM.
5 require 'rexml/parsers/sax2parser'
9 if defined?(SystemTimer)
16 # The base class for API Errors.
17 class APIError < RuntimeError
19 :internal_server_error
27 # Raised when an API object is not found.
28 class APINotFoundError < APIError
38 # Raised when a precondition to an API action fails sanity check.
39 class APIPreconditionFailedError < APIError
40 def initialize(message = "")
49 "Precondition failed: #{@message}"
53 # Raised when to delete an already-deleted object.
54 class APIAlreadyDeletedError < APIError
55 def initialize(object = "object", object_id = "")
56 @object, @object_id = object, object_id
59 attr_reader :object, :object_id
66 "The #{object} with the id #{object_id} has already been deleted"
70 # Raised when the user logged in isn't the same as the changeset
71 class APIUserChangesetMismatchError < APIError
77 "The user doesn't own that changeset"
81 # Raised when the changeset provided is already closed
82 class APIChangesetAlreadyClosedError < APIError
83 def initialize(changeset)
84 @changeset = changeset
87 attr_reader :changeset
94 "The changeset #{@changeset.id} was closed at #{@changeset.closed_at}"
98 # Raised when a change is expecting a changeset, but the changeset doesn't exist
99 class APIChangesetMissingError < APIError
105 "You need to supply a changeset to be able to make a change"
109 # Raised when a diff is uploaded containing many changeset IDs which don't match
110 # the changeset ID that the diff was uploaded to.
111 class APIChangesetMismatchError < APIError
112 def initialize(provided, allowed)
113 @provided, @allowed = provided, allowed
121 "Changeset mismatch: Provided #{@provided} but only #{@allowed} is allowed"
125 # Raised when a diff upload has an unknown action. You can only have create,
127 class APIChangesetActionInvalid < APIError
128 def initialize(provided)
137 "Unknown action #{@provided}, choices are create, modify, delete"
141 # Raised when bad XML is encountered which stops things parsing as
143 class APIBadXMLError < APIError
144 def initialize(model, xml, message="")
145 @model, @xml, @message = model, xml, message
153 "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}"
157 # Raised when the provided version is not equal to the latest in the db.
158 class APIVersionMismatchError < APIError
159 def initialize(id, type, provided, latest)
160 @id, @type, @provided, @latest = id, type, provided, latest
163 attr_reader :provided, :latest, :id, :type
170 "Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}"
174 # raised when a two tags have a duplicate key string in an element.
175 # this is now forbidden by the API.
176 class APIDuplicateTagsError < APIError
177 def initialize(type, id, tag_key)
178 @type, @id, @tag_key = type, id, tag_key
181 attr_reader :type, :id, :tag_key
188 "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}"
192 # Raised when a way has more than the configured number of way nodes.
193 # This prevents ways from being to long and difficult to work with
194 class APITooManyWayNodesError < APIError
195 def initialize(id, provided, max)
196 @id, @provided, @max = id, provided, max
199 attr_reader :id, :provided, :max
206 "You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed"
211 # raised when user input couldn't be parsed
212 class APIBadUserInput < APIError
213 def initialize(message)
227 # raised when bounding box is invalid
228 class APIBadBoundingBox < APIError
229 def initialize(message)
243 # raised when an API call is made using a method not supported on that URI
244 class APIBadMethodError < APIError
245 def initialize(supported_method)
246 @supported_method = supported_method
254 "Only method #{@supported_method} is supported on this URI"
259 # raised when an API call takes too long
260 class APITimeoutError < APIError
271 # raised when someone tries to redact a current version of
272 # an element - only historical versions can be redacted.
273 class APICannotRedactError < APIError
279 "Cannot redact current version of element, only historical versions may be redacted."
283 # Raised when the note provided is already closed
284 class APINoteAlreadyClosedError < APIError
296 "The note #{@note.id} was closed at #{@note.closed_at}"
300 # Raised when the note provided is already open
301 class APINoteAlreadyOpenError < APIError
313 "The note #{@note.id} is already open"
317 # raised when a two preferences have a duplicate key string.
318 class APIDuplicatePreferenceError < APIError
330 "Duplicate preferences with key #{@key}"
334 # Helper methods for going to/from mercator and lat/lng.
338 #init me with your bounding box and the size of your image
339 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
340 xsize = xsheet(max_lon) - xsheet(min_lon)
341 ysize = ysheet(max_lat) - ysheet(min_lat)
342 xscale = xsize / width
343 yscale = ysize / height
344 scale = [xscale, yscale].max
346 xpad = width * scale - xsize
347 ypad = height * scale - ysize
352 @tx = xsheet(min_lon) - xpad / 2
353 @ty = ysheet(min_lat) - ypad / 2
355 @bx = xsheet(max_lon) + xpad / 2
356 @by = ysheet(max_lat) + ypad / 2
359 #the following two functions will give you the x/y on the entire sheet
362 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
369 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
372 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
376 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
383 # initialise with a base position
384 def initialize(lat, lon)
385 @lat = lat * PI / 180
386 @lon = lon * PI / 180
389 # get the distance from the base position to a given position
390 def distance(lat, lon)
393 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
396 # get the worst case bounds for a given radius from the base position
398 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
401 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
406 minlat = (@lat - latradius) * 180 / PI
407 maxlat = (@lat + latradius) * 180 / PI
408 minlon = (@lon - lonradius) * 180 / PI
409 maxlon = (@lon + lonradius) * 180 / PI
411 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
414 # get the SQL to use to calculate distance
415 def sql_for_distance(lat_field, lon_field)
416 "6372.795 * 2 * asin(sqrt(power(sin((radians(#{lat_field}) - #{@lat}) / 2), 2) + cos(#{@lat}) * cos(radians(#{lat_field})) * power(sin((radians(#{lon_field}) - #{@lon})/2), 2)))"
421 def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
422 @doc = XML::Document.new
423 @doc.encoding = XML::Encoding::UTF_8
425 rss = XML::Node.new 'rss'
427 rss['version'] = "2.0"
428 rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
429 @channel = XML::Node.new 'channel'
431 title = XML::Node.new 'title'
434 description_el = XML::Node.new 'description'
435 @channel << description_el
437 description_el << feed_description
438 link = XML::Node.new 'link'
441 image = XML::Node.new 'image'
443 url = XML::Node.new 'url'
444 url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
446 title = XML::Node.new 'title'
447 title << "OpenStreetMap"
449 width = XML::Node.new 'width'
452 height = XML::Node.new 'height'
455 link = XML::Node.new 'link'
460 def add(latitude=0, longitude=0, title_text='dummy title', author_text='anonymous', url='http://www.example.com/', description_text='dummy description', timestamp=DateTime.now)
461 item = XML::Node.new 'item'
463 title = XML::Node.new 'title'
466 link = XML::Node.new 'link'
470 guid = XML::Node.new 'guid'
474 description = XML::Node.new 'description'
475 description << description_text
478 author = XML::Node.new 'author'
479 author << author_text
482 pubDate = XML::Node.new 'pubDate'
483 pubDate << timestamp.to_s(:rfc822)
487 lat_el = XML::Node.new 'geo:lat'
488 lat_el << latitude.to_s
493 lon_el = XML::Node.new 'geo:long'
494 lon_el << longitude.to_s
508 doc = XML::Document.new
509 doc.encoding = XML::Encoding::UTF_8
510 root = XML::Node.new 'osm'
511 root['version'] = API_VERSION.to_s
512 root['generator'] = GENERATOR
513 root['copyright'] = COPYRIGHT_OWNER
514 root['attribution'] = ATTRIBUTION_URL
515 root['license'] = LICENSE_URL
521 def self.IPToCountry(ip_address)
523 ipinfo = Quova::IpInfo.new(ip_address)
525 if ipinfo.status == Quova::Success then
526 country = ipinfo.country_code
528 Net::HTTP.start('api.hostip.info') do |http|
529 country = http.get("/country.php?ip=#{ip_address}").body
530 country = "GB" if country == "UK"
534 return country.upcase
542 def self.IPLocation(ip_address)
543 code = OSM.IPToCountry(ip_address)
545 if code and country = Country.find_by_code(code)
546 return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
552 # Parse a float, raising a specified exception on failure
553 def self.parse_float(str, klass, *args)
556 raise klass.new(*args)
559 # Construct a random token of a given length
560 def self.make_token(length = 30)
561 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
565 token += chars[(rand * chars.length).to_i].chr
571 # Return an SQL fragment to select a given area of the globe
572 def self.sql_for_area(bbox, prefix = nil)
573 tilesql = QuadTile.sql_for_area(bbox, prefix)
574 bbox = bbox.to_scaled
576 return "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " +
577 "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
580 def self.legal_text_for_country(country_code)
581 file_name = File.join(Rails.root, "config", "legales", country_code.to_s + ".yml")
582 file_name = File.join(Rails.root, "config", "legales", DEFAULT_LEGALE + ".yml") unless File.exist? file_name
583 YAML::load_file(file_name)