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 provided version is not equal to the latest in the db.
37 class APIVersionMismatchError < APIError
38 def initialize(provided, latest)
39 @provided, @latest = provided, latest
42 attr_reader :provided, :latest
45 { :text => "Version mismatch: Provided " + ex.provided.to_s +
46 ", server had: " + ex.latest.to_s, :status => :bad_request }
50 # Helper methods for going to/from mercator and lat/lng.
54 #init me with your bounding box and the size of your image
55 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
56 xsize = xsheet(max_lon) - xsheet(min_lon)
57 ysize = ysheet(max_lat) - ysheet(min_lat)
58 xscale = xsize / width
59 yscale = ysize / height
60 scale = [xscale, yscale].max
62 xpad = width * scale - xsize
63 ypad = height * scale - ysize
68 @tx = xsheet(min_lon) - xpad / 2
69 @ty = ysheet(min_lat) - ypad / 2
71 @bx = xsheet(max_lon) + xpad / 2
72 @by = ysheet(max_lat) + ypad / 2
75 #the following two functions will give you the x/y on the entire sheet
78 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
85 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
88 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
92 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
97 # This piece of magic reads a GPX with SAX and spits out
100 # This would print every latitude value:
102 # gpx = OSM::GPXImporter.new('somefile.gpx')
103 # gpx.points {|p| puts p['latitude']}
105 # FIXME swap REXML for libXML
106 attr_reader :possible_points
107 attr_reader :actual_points
108 attr_reader :tracksegs
122 date = DateTime.now();
129 parser = REXML::Parsers::SAX2Parser.new(@file)
131 parser.listen( :start_element, %w{ trkpt }) do |uri,localname,qname,attributes|
132 lat = attributes['lat'].to_f
133 lon = attributes['lon'].to_f
137 @possible_points += 1
140 parser.listen( :characters, %w{ ele } ) do |text|
145 parser.listen( :characters, %w{ time } ) do |text|
146 if text && text != ''
148 date = DateTime.parse(text)
155 parser.listen( :end_element, %w{ trkseg } ) do |uri, localname, qname|
159 parser.listen( :end_element, %w{ trkpt } ) do |uri,localname,qname|
160 if gotlatlon && gotdate
161 ele = '0' unless gotele
162 if lat < 90 && lat > -90 && lon > -180 && lon < 180
164 yield Hash['latitude' => lat, 'longitude' => lon, 'timestamp' => date, 'altitude' => ele, 'segment' => @tracksegs]
175 def get_picture(min_lat, min_lon, max_lat, max_lon, num_points)
176 #puts "getting picfor bbox #{min_lat},#{min_lon} - #{max_lat},#{max_lon}"
180 proj = OSM::Mercator.new(min_lat, min_lon, max_lat, max_lon, width, height)
182 linegc = Magick::Draw.new
183 linegc.stroke_linejoin('miter')
184 linegc.stroke_width(1)
185 linegc.stroke('#BBBBBB')
186 linegc.fill('#BBBBBB')
188 highlightgc = Magick::Draw.new
189 highlightgc.stroke_linejoin('miter')
190 highlightgc.stroke_width(3)
191 highlightgc.stroke('#000000')
192 highlightgc.fill('#000000')
197 image = Magick::Image.new(width, height) do |image|
198 image.background_color = 'white'
213 px = proj.x(p['longitude'])
214 py = proj.y(p['latitude'])
224 gc.line(px, py, oldpx, oldpy)
231 if m > num_points.to_f / frames.to_f * (mm+1)
239 il = Magick::ImageList.new
251 def get_icon(min_lat, min_lon, max_lat, max_lon)
252 #puts "getting icon for bbox #{min_lat},#{min_lon} - #{max_lat},#{max_lon}"
255 proj = OSM::Mercator.new(min_lat, min_lon, max_lat, max_lon, width, height)
257 gc = Magick::Draw.new
258 gc.stroke_linejoin('miter')
263 image = Magick::Image.new(width, height) do |image|
264 image.background_color = 'white'
274 px = proj.x(p['longitude'])
275 py = proj.y(p['latitude'])
277 gc.dup.line(px, py, oldpx, oldpy).draw(image) unless first
292 # initialise with a base position
293 def initialize(lat, lon)
294 @lat = lat * PI / 180
295 @lon = lon * PI / 180
298 # get the distance from the base position to a given position
299 def distance(lat, lon)
302 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
305 # get the worst case bounds for a given radius from the base position
307 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
308 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
309 minlat = (@lat - latradius) * 180 / PI
310 maxlat = (@lat + latradius) * 180 / PI
311 minlon = (@lon - lonradius) * 180 / PI
312 maxlon = (@lon + lonradius) * 180 / PI
313 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
318 def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
319 @doc = XML::Document.new
320 @doc.encoding = 'UTF-8'
322 rss = XML::Node.new 'rss'
324 rss['version'] = "2.0"
325 rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
326 @channel = XML::Node.new 'channel'
328 title = XML::Node.new 'title'
331 description_el = XML::Node.new 'description'
332 @channel << description_el
334 description_el << feed_description
335 link = XML::Node.new 'link'
338 image = XML::Node.new 'image'
340 url = XML::Node.new 'url'
341 url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
343 title = XML::Node.new 'title'
344 title << "OpenStreetMap"
346 width = XML::Node.new 'width'
349 height = XML::Node.new 'height'
352 link = XML::Node.new 'link'
357 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)
358 item = XML::Node.new 'item'
360 title = XML::Node.new 'title'
363 link = XML::Node.new 'link'
367 guid = XML::Node.new 'guid'
371 description = XML::Node.new 'description'
372 description << description_text
375 author = XML::Node.new 'author'
376 author << author_text
379 pubDate = XML::Node.new 'pubDate'
380 pubDate << timestamp.to_s(:rfc822)
384 lat_el = XML::Node.new 'geo:lat'
385 lat_el << latitude.to_s
390 lon_el = XML::Node.new 'geo:long'
391 lon_el << longitude.to_s
405 doc = XML::Document.new
406 doc.encoding = 'UTF-8'
407 root = XML::Node.new 'osm'
408 root['version'] = API_VERSION
409 root['generator'] = 'OpenStreetMap server'
415 def self.IPLocation(ip_address)
416 Timeout::timeout(4) do
417 Net::HTTP.start('api.hostip.info') do |http|
418 country = http.get("/country.php?ip=#{ip_address}").body
419 country = "GB" if country == "UK"
420 Net::HTTP.start('ws.geonames.org') do |http|
421 xml = REXML::Document.new(http.get("/countryInfo?country=#{country}").body)
422 xml.elements.each("geonames/country") do |ele|
423 minlon = ele.get_text("bBoxWest").to_s
424 minlat = ele.get_text("bBoxSouth").to_s
425 maxlon = ele.get_text("bBoxEast").to_s
426 maxlat = ele.get_text("bBoxNorth").to_s
427 return { :minlon => minlon, :minlat => minlat, :maxlon => maxlon, :maxlat => maxlat }
438 # Construct a random token of a given length
439 def self.make_token(length = 30)
440 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
444 token += chars[(rand * chars.length).to_i].chr
450 # Return an encrypted version of a password
451 def self.encrypt_password(password, salt)
452 return Digest::MD5.hexdigest(password) if salt.nil?
453 return Digest::MD5.hexdigest(salt + password)
456 # Return an SQL fragment to select a given area of the globe
457 def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
458 tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
459 minlat = (minlat * 10000000).round
460 minlon = (minlon * 10000000).round
461 maxlat = (maxlat * 10000000).round
462 maxlon = (maxlon * 10000000).round
464 return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"