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 { :text => "", :status => :internal_server_error }
18 # Raised when an API object is not found.
19 class APINotFoundError < APIError
21 { :nothing => true, :status => :not_found }
25 # Raised when a precondition to an API action fails sanity check.
26 class APIPreconditionFailedError < APIError
28 { :text => "", :status => :precondition_failed }
32 # Raised when to delete an already-deleted object.
33 class APIAlreadyDeletedError < APIError
35 { :text => "", :status => :gone }
39 # Raised when the user logged in isn't the same as the changeset
40 class APIUserChangesetMismatchError < APIError
42 { :text => "The user doesn't own that changeset", :status => :conflict }
46 # Raised when the changeset provided is already closed
47 class APIChangesetAlreadyClosedError < APIError
48 def initialize(changeset)
49 @changeset = changeset
52 attr_reader :changeset
55 { :text => "The changeset #{@changeset.id} was closed at #{@changeset.closed_at}.", :status => :conflict }
59 # Raised when a change is expecting a changeset, but the changeset doesn't exist
60 class APIChangesetMissingError < APIError
62 { :text => "You need to supply a changeset to be able to make a change", :status => :conflict }
66 # Raised when a diff is uploaded containing many changeset IDs which don't match
67 # the changeset ID that the diff was uploaded to.
68 class APIChangesetMismatchError < APIError
69 def initialize(provided, allowed)
70 @provided, @allowed = provided, allowed
74 { :text => "Changeset mismatch: Provided #{@provided} but only " +
75 "#{@allowed} is allowed.", :status => :conflict }
79 # Raised when a diff upload has an unknown action. You can only have create,
81 class APIChangesetActionInvalid < APIError
82 def initialize(provided)
87 { :text => "Unknown action #{@provided}, choices are create, modify, delete.",
88 :status => :bad_request }
92 # Raised when bad XML is encountered which stops things parsing as
94 class APIBadXMLError < APIError
95 def initialize(model, xml)
96 @model, @xml = model, xml
100 { :text => "Cannot parse valid #{@model} from xml string #{@xml}",
101 :status => :bad_request }
105 # Raised when the provided version is not equal to the latest in the db.
106 class APIVersionMismatchError < APIError
107 def initialize(id, type, provided, latest)
108 @id, @type, @provided, @latest = id, type, provided, latest
111 attr_reader :provided, :latest, :id, :type
114 { :text => "Version mismatch: Provided " + provided.to_s +
115 ", server had: " + latest.to_s + " of " + type + " " + id.to_s,
116 :status => :conflict }
120 # raised when a two tags have a duplicate key string in an element.
121 # this is now forbidden by the API.
122 class APIDuplicateTagsError < APIError
123 def initialize(type, id, tag_key)
124 @type, @id, @tag_key = type, id, tag_key
127 attr_reader :type, :id, :tag_key
130 { :text => "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}.",
131 :status => :bad_request }
135 # Raised when a way has more than the configured number of way nodes.
136 # This prevents ways from being to long and difficult to work with
137 class APITooManyWayNodesError < APIError
138 def initialize(provided, max)
139 @provided, @max = provided, max
142 attr_reader :provided, :max
145 { :text => "You tried to add #{provided} nodes to the way, however only #{max} are allowed",
146 :status => :bad_request }
151 # raised when user input couldn't be parsed
152 class APIBadUserInput < APIError
153 def initialize(message)
158 { :text => message, :mime_type => "text/plain", :status => :bad_request }
162 # Helper methods for going to/from mercator and lat/lng.
166 #init me with your bounding box and the size of your image
167 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
168 xsize = xsheet(max_lon) - xsheet(min_lon)
169 ysize = ysheet(max_lat) - ysheet(min_lat)
170 xscale = xsize / width
171 yscale = ysize / height
172 scale = [xscale, yscale].max
174 xpad = width * scale - xsize
175 ypad = height * scale - ysize
180 @tx = xsheet(min_lon) - xpad / 2
181 @ty = ysheet(min_lat) - ypad / 2
183 @bx = xsheet(max_lon) + xpad / 2
184 @by = ysheet(max_lat) + ypad / 2
187 #the following two functions will give you the x/y on the entire sheet
190 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
197 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
200 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
204 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
211 # initialise with a base position
212 def initialize(lat, lon)
213 @lat = lat * PI / 180
214 @lon = lon * PI / 180
217 # get the distance from the base position to a given position
218 def distance(lat, lon)
221 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
224 # get the worst case bounds for a given radius from the base position
226 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
227 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
228 minlat = (@lat - latradius) * 180 / PI
229 maxlat = (@lat + latradius) * 180 / PI
230 minlon = (@lon - lonradius) * 180 / PI
231 maxlon = (@lon + lonradius) * 180 / PI
232 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
237 def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
238 @doc = XML::Document.new
239 @doc.encoding = 'UTF-8'
241 rss = XML::Node.new 'rss'
243 rss['version'] = "2.0"
244 rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
245 @channel = XML::Node.new 'channel'
247 title = XML::Node.new 'title'
250 description_el = XML::Node.new 'description'
251 @channel << description_el
253 description_el << feed_description
254 link = XML::Node.new 'link'
257 image = XML::Node.new 'image'
259 url = XML::Node.new 'url'
260 url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
262 title = XML::Node.new 'title'
263 title << "OpenStreetMap"
265 width = XML::Node.new 'width'
268 height = XML::Node.new 'height'
271 link = XML::Node.new 'link'
276 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)
277 item = XML::Node.new 'item'
279 title = XML::Node.new 'title'
282 link = XML::Node.new 'link'
286 guid = XML::Node.new 'guid'
290 description = XML::Node.new 'description'
291 description << description_text
294 author = XML::Node.new 'author'
295 author << author_text
298 pubDate = XML::Node.new 'pubDate'
299 pubDate << timestamp.to_s(:rfc822)
303 lat_el = XML::Node.new 'geo:lat'
304 lat_el << latitude.to_s
309 lon_el = XML::Node.new 'geo:long'
310 lon_el << longitude.to_s
324 doc = XML::Document.new
325 doc.encoding = 'UTF-8'
326 root = XML::Node.new 'osm'
327 root['version'] = API_VERSION
328 root['generator'] = GENERATOR
334 def self.IPLocation(ip_address)
335 Timeout::timeout(4) do
336 Net::HTTP.start('api.hostip.info') do |http|
337 country = http.get("/country.php?ip=#{ip_address}").body
338 country = "GB" if country == "UK"
339 Net::HTTP.start('ws.geonames.org') do |http|
340 xml = REXML::Document.new(http.get("/countryInfo?country=#{country}").body)
341 xml.elements.each("geonames/country") do |ele|
342 minlon = ele.get_text("bBoxWest").to_s
343 minlat = ele.get_text("bBoxSouth").to_s
344 maxlon = ele.get_text("bBoxEast").to_s
345 maxlat = ele.get_text("bBoxNorth").to_s
346 return { :minlon => minlon, :minlat => minlat, :maxlon => maxlon, :maxlat => maxlat }
357 # Construct a random token of a given length
358 def self.make_token(length = 30)
359 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
363 token += chars[(rand * chars.length).to_i].chr
369 # Return an encrypted version of a password
370 def self.encrypt_password(password, salt)
371 return Digest::MD5.hexdigest(password) if salt.nil?
372 return Digest::MD5.hexdigest(salt + password)
375 # Return an SQL fragment to select a given area of the globe
376 def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
377 tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
378 minlat = (minlat * 10000000).round
379 minlon = (minlon * 10000000).round
380 maxlat = (maxlat * 10000000).round
381 maxlon = (maxlon * 10000000).round
383 return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"