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
22 # Raised when a precondition to an API action fails sanity check.
23 class APIPreconditionFailedError < APIError
25 { :text => "", :status => :precondition_failed }
29 # Raised when to delete an already-deleted object.
30 class APIAlreadyDeletedError < APIError
32 { :text => "", :status => :gone }
36 # Raised when the user logged in isn't the same as the changeset
37 class APIUserChangesetMismatchError < APIError
39 { :text => "The user doesn't own that changeset", :status => :conflict }
43 # Raised when the changeset provided is already closed
44 class APIChangesetAlreadyClosedError < APIError
46 { :text => "The supplied changeset has already been closed", :status => :conflict }
50 # Raised when a change is expecting a changeset, but the changeset doesn't exist
51 class APIChangesetMissingError < APIError
53 { :text => "You need to supply a changeset to be able to make a change", :status => :conflict }
57 # Raised when a diff is uploaded containing many changeset IDs which don't match
58 # the changeset ID that the diff was uploaded to.
59 class APIChangesetMismatchError < APIError
60 def initialize(provided, allowed)
61 @provided, @allowed = provided, allowed
65 { :text => "Changeset mismatch: Provided #{@provided} but only " +
66 "#{@allowed} is allowed.", :status => :conflict }
70 # Raised when a diff upload has an unknown action. You can only have create,
72 class APIChangesetActionInvalid < APIError
73 def initialize(provided)
78 { :text => "Unknown action #{@provided}, choices are create, modify, delete.",
79 :status => :bad_request }
83 # Raised when bad XML is encountered which stops things parsing as
85 class APIBadXMLError < APIError
86 def initialize(model, xml)
87 @model, @xml = model, xml
91 { :text => "Cannot parse valid #{@model} from xml string #{@xml}",
92 :status => :bad_request }
96 # Raised when the provided version is not equal to the latest in the db.
97 class APIVersionMismatchError < APIError
98 def initialize(provided, latest)
99 @provided, @latest = provided, latest
102 attr_reader :provided, :latest
105 { :text => "Version mismatch: Provided " + provided.to_s +
106 ", server had: " + latest.to_s, :status => :conflict }
110 # raised when a two tags have a duplicate key string in an element.
111 # this is now forbidden by the API.
112 class APIDuplicateTagsError < APIError
113 def initialize(type, id, tag_key)
114 @type, @id, @tag_key = type, id, tag_key
117 attr_reader :type, :id, :tag_key
120 { :text => "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}.",
121 :status => :bad_request }
125 # Raised when a way has more than the configured number of way nodes.
126 # This prevents ways from being to long and difficult to work with
127 class APITooManyWayNodesError < APIError
128 def initialize(provided, max)
129 @provided, @max = provided, max
132 attr_reader :provided, :max
135 { :text => "You tried to add #{provided} nodes to the way, however only #{max} are allowed",
136 :status => :bad_request }
140 # Helper methods for going to/from mercator and lat/lng.
144 #init me with your bounding box and the size of your image
145 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
146 xsize = xsheet(max_lon) - xsheet(min_lon)
147 ysize = ysheet(max_lat) - ysheet(min_lat)
148 xscale = xsize / width
149 yscale = ysize / height
150 scale = [xscale, yscale].max
152 xpad = width * scale - xsize
153 ypad = height * scale - ysize
158 @tx = xsheet(min_lon) - xpad / 2
159 @ty = ysheet(min_lat) - ypad / 2
161 @bx = xsheet(max_lon) + xpad / 2
162 @by = ysheet(max_lat) + ypad / 2
165 #the following two functions will give you the x/y on the entire sheet
168 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
175 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
178 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
182 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
189 # initialise with a base position
190 def initialize(lat, lon)
191 @lat = lat * PI / 180
192 @lon = lon * PI / 180
195 # get the distance from the base position to a given position
196 def distance(lat, lon)
199 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
202 # get the worst case bounds for a given radius from the base position
204 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
205 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
206 minlat = (@lat - latradius) * 180 / PI
207 maxlat = (@lat + latradius) * 180 / PI
208 minlon = (@lon - lonradius) * 180 / PI
209 maxlon = (@lon + lonradius) * 180 / PI
210 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
215 def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
216 @doc = XML::Document.new
217 @doc.encoding = 'UTF-8'
219 rss = XML::Node.new 'rss'
221 rss['version'] = "2.0"
222 rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
223 @channel = XML::Node.new 'channel'
225 title = XML::Node.new 'title'
228 description_el = XML::Node.new 'description'
229 @channel << description_el
231 description_el << feed_description
232 link = XML::Node.new 'link'
235 image = XML::Node.new 'image'
237 url = XML::Node.new 'url'
238 url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
240 title = XML::Node.new 'title'
241 title << "OpenStreetMap"
243 width = XML::Node.new 'width'
246 height = XML::Node.new 'height'
249 link = XML::Node.new 'link'
254 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)
255 item = XML::Node.new 'item'
257 title = XML::Node.new 'title'
260 link = XML::Node.new 'link'
264 guid = XML::Node.new 'guid'
268 description = XML::Node.new 'description'
269 description << description_text
272 author = XML::Node.new 'author'
273 author << author_text
276 pubDate = XML::Node.new 'pubDate'
277 pubDate << timestamp.to_s(:rfc822)
281 lat_el = XML::Node.new 'geo:lat'
282 lat_el << latitude.to_s
287 lon_el = XML::Node.new 'geo:long'
288 lon_el << longitude.to_s
302 doc = XML::Document.new
303 doc.encoding = 'UTF-8'
304 root = XML::Node.new 'osm'
305 root['version'] = API_VERSION
306 root['generator'] = GENERATOR
312 def self.IPLocation(ip_address)
313 Timeout::timeout(4) do
314 Net::HTTP.start('api.hostip.info') do |http|
315 country = http.get("/country.php?ip=#{ip_address}").body
316 country = "GB" if country == "UK"
317 Net::HTTP.start('ws.geonames.org') do |http|
318 xml = REXML::Document.new(http.get("/countryInfo?country=#{country}").body)
319 xml.elements.each("geonames/country") do |ele|
320 minlon = ele.get_text("bBoxWest").to_s
321 minlat = ele.get_text("bBoxSouth").to_s
322 maxlon = ele.get_text("bBoxEast").to_s
323 maxlat = ele.get_text("bBoxNorth").to_s
324 return { :minlon => minlon, :minlat => minlat, :maxlon => maxlon, :maxlat => maxlat }
335 # Construct a random token of a given length
336 def self.make_token(length = 30)
337 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
341 token += chars[(rand * chars.length).to_i].chr
347 # Return an encrypted version of a password
348 def self.encrypt_password(password, salt)
349 return Digest::MD5.hexdigest(password) if salt.nil?
350 return Digest::MD5.hexdigest(salt + password)
353 # Return an SQL fragment to select a given area of the globe
354 def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
355 tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
356 minlat = (minlat * 10000000).round
357 minlon = (minlon * 10000000).round
358 maxlat = (maxlat * 10000000).round
359 maxlon = (maxlon * 10000000).round
361 return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"