1 # The OSM module provides support functions for OSM.
5 require 'rexml/parsers/sax2parser'
11 # The base class for API Errors.
12 class APIError < RuntimeError
14 :internal_server_error
22 # Raised when an API object is not found.
23 class APINotFoundError < APIError
33 # Raised when a precondition to an API action fails sanity check.
34 class APIPreconditionFailedError < APIError
35 def initialize(message = "")
44 "Precondition failed: #{@message}"
48 # Raised when to delete an already-deleted object.
49 class APIAlreadyDeletedError < APIError
50 def initialize(object = "object", object_id = "")
51 @object, @object_id = object, object_id
54 attr_reader :object, :object_id
61 "The #{object} with the id #{object_id} has already been deleted"
65 # Raised when the user logged in isn't the same as the changeset
66 class APIUserChangesetMismatchError < APIError
72 "The user doesn't own that changeset"
76 # Raised when the changeset provided is already closed
77 class APIChangesetAlreadyClosedError < APIError
78 def initialize(changeset)
79 @changeset = changeset
82 attr_reader :changeset
89 "The changeset #{@changeset.id} was closed at #{@changeset.closed_at}"
93 # Raised when a change is expecting a changeset, but the changeset doesn't exist
94 class APIChangesetMissingError < APIError
100 "You need to supply a changeset to be able to make a change"
104 # Raised when a diff is uploaded containing many changeset IDs which don't match
105 # the changeset ID that the diff was uploaded to.
106 class APIChangesetMismatchError < APIError
107 def initialize(provided, allowed)
108 @provided, @allowed = provided, allowed
116 "Changeset mismatch: Provided #{@provided} but only #{@allowed} is allowed"
120 # Raised when a diff upload has an unknown action. You can only have create,
122 class APIChangesetActionInvalid < APIError
123 def initialize(provided)
132 "Unknown action #{@provided}, choices are create, modify, delete"
136 # Raised when bad XML is encountered which stops things parsing as
138 class APIBadXMLError < APIError
139 def initialize(model, xml, message="")
140 @model, @xml, @message = model, xml, message
148 "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}"
152 # Raised when the provided version is not equal to the latest in the db.
153 class APIVersionMismatchError < APIError
154 def initialize(id, type, provided, latest)
155 @id, @type, @provided, @latest = id, type, provided, latest
158 attr_reader :provided, :latest, :id, :type
165 "Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}"
169 # raised when a two tags have a duplicate key string in an element.
170 # this is now forbidden by the API.
171 class APIDuplicateTagsError < APIError
172 def initialize(type, id, tag_key)
173 @type, @id, @tag_key = type, id, tag_key
176 attr_reader :type, :id, :tag_key
183 "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}"
187 # Raised when a way has more than the configured number of way nodes.
188 # This prevents ways from being to long and difficult to work with
189 class APITooManyWayNodesError < APIError
190 def initialize(id, provided, max)
191 @id, @provided, @max = id, provided, max
194 attr_reader :id, :provided, :max
201 "You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed"
206 # raised when user input couldn't be parsed
207 class APIBadUserInput < APIError
208 def initialize(message)
222 # raised when bounding box is invalid
223 class APIBadBoundingBox < APIError
224 def initialize(message)
238 # raised when an API call is made using a method not supported on that URI
239 class APIBadMethodError < APIError
240 def initialize(supported_method)
241 @supported_method = supported_method
249 "Only method #{@supported_method} is supported on this URI"
254 # raised when an API call takes too long
255 class APITimeoutError < APIError
265 # Helper methods for going to/from mercator and lat/lng.
269 #init me with your bounding box and the size of your image
270 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
271 xsize = xsheet(max_lon) - xsheet(min_lon)
272 ysize = ysheet(max_lat) - ysheet(min_lat)
273 xscale = xsize / width
274 yscale = ysize / height
275 scale = [xscale, yscale].max
277 xpad = width * scale - xsize
278 ypad = height * scale - ysize
283 @tx = xsheet(min_lon) - xpad / 2
284 @ty = ysheet(min_lat) - ypad / 2
286 @bx = xsheet(max_lon) + xpad / 2
287 @by = ysheet(max_lat) + ypad / 2
290 #the following two functions will give you the x/y on the entire sheet
293 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
300 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
303 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
307 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
314 # initialise with a base position
315 def initialize(lat, lon)
316 @lat = lat * PI / 180
317 @lon = lon * PI / 180
320 # get the distance from the base position to a given position
321 def distance(lat, lon)
324 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
327 # get the worst case bounds for a given radius from the base position
329 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
332 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
337 minlat = (@lat - latradius) * 180 / PI
338 maxlat = (@lat + latradius) * 180 / PI
339 minlon = (@lon - lonradius) * 180 / PI
340 maxlon = (@lon + lonradius) * 180 / PI
342 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
345 # get the SQL to use to calculate distance
346 def sql_for_distance(lat_field, lon_field)
347 "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)))"
352 def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
353 @doc = XML::Document.new
354 @doc.encoding = XML::Encoding::UTF_8
356 rss = XML::Node.new 'rss'
358 rss['version'] = "2.0"
359 rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
360 @channel = XML::Node.new 'channel'
362 title = XML::Node.new 'title'
365 description_el = XML::Node.new 'description'
366 @channel << description_el
368 description_el << feed_description
369 link = XML::Node.new 'link'
372 image = XML::Node.new 'image'
374 url = XML::Node.new 'url'
375 url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
377 title = XML::Node.new 'title'
378 title << "OpenStreetMap"
380 width = XML::Node.new 'width'
383 height = XML::Node.new 'height'
386 link = XML::Node.new 'link'
391 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)
392 item = XML::Node.new 'item'
394 title = XML::Node.new 'title'
397 link = XML::Node.new 'link'
401 guid = XML::Node.new 'guid'
405 description = XML::Node.new 'description'
406 description << description_text
409 author = XML::Node.new 'author'
410 author << author_text
413 pubDate = XML::Node.new 'pubDate'
414 pubDate << timestamp.to_s(:rfc822)
418 lat_el = XML::Node.new 'geo:lat'
419 lat_el << latitude.to_s
424 lon_el = XML::Node.new 'geo:long'
425 lon_el << longitude.to_s
439 doc = XML::Document.new
440 doc.encoding = XML::Encoding::UTF_8
441 root = XML::Node.new 'osm'
442 root['version'] = API_VERSION
443 root['generator'] = GENERATOR
449 def self.IPLocation(ip_address)
450 Timeout::timeout(4) do
451 ipinfo = Quova::IpInfo.new(ip_address)
453 if ipinfo.status == Quova::Success then
454 country = ipinfo.country_code
456 Net::HTTP.start('api.hostip.info') do |http|
457 country = http.get("/country.php?ip=#{ip_address}").body
458 country = "GB" if country == "UK"
462 country = Country.find_by_code(country.upcase)
464 return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
472 # Construct a random token of a given length
473 def self.make_token(length = 30)
474 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
478 token += chars[(rand * chars.length).to_i].chr
484 # Return an encrypted version of a password
485 def self.encrypt_password(password, salt)
486 return Digest::MD5.hexdigest(password) if salt.nil?
487 return Digest::MD5.hexdigest(salt + password)
490 # Return an SQL fragment to select a given area of the globe
491 def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
492 tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
493 minlat = (minlat * 10000000).round
494 minlon = (minlon * 10000000).round
495 maxlat = (maxlat * 10000000).round
496 maxlon = (maxlon * 10000000).round
498 return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"
501 # Return an SQL fragment to select a given area of the globe without using the quadtile index
502 def self.sql_for_area_no_quadtile(minlat, minlon, maxlat, maxlon, prefix = nil, without_quadtile = :false)
503 minlat = (minlat * 10000000).round
504 minlon = (minlon * 10000000).round
505 maxlat = (maxlat * 10000000).round
506 maxlon = (maxlon * 10000000).round
508 return "#{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"