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
13 def render_opts { :text => "", :status => :internal_server_error } end
16 # Raised when an API object is not found.
17 class APINotFoundError < APIError
20 # Raised when a precondition to an API action fails sanity check.
21 class APIPreconditionFailedError < APIError
22 def render_opts { :text => "", :status => :precondition_failed } end
25 # Raised when to delete an already-deleted object.
26 class APIAlreadyDeletedError < APIError
27 def render_opts { :text => "", :status => :gone } end
30 # Raised when the provided version is not equal to the latest in the db.
31 class APIVersionMismatchError < APIError
32 def initialize(provided, latest)
33 @provided, @latest = provided, latest
36 attr_reader :provided, :latest
39 { :text => "Version mismatch: Provided " + ex.provided.to_s +
40 ", server had: " + ex.latest.to_s, :status => :bad_request }
44 # Helper methods for going to/from mercator and lat/lng.
48 #init me with your bounding box and the size of your image
49 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
50 xsize = xsheet(max_lon) - xsheet(min_lon)
51 ysize = ysheet(max_lat) - ysheet(min_lat)
52 xscale = xsize / width
53 yscale = ysize / height
54 scale = [xscale, yscale].max
56 xpad = width * scale - xsize
57 ypad = height * scale - ysize
62 @tx = xsheet(min_lon) - xpad / 2
63 @ty = ysheet(min_lat) - ypad / 2
65 @bx = xsheet(max_lon) + xpad / 2
66 @by = ysheet(max_lat) + ypad / 2
69 #the following two functions will give you the x/y on the entire sheet
72 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
79 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
82 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
86 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
91 # This piece of magic reads a GPX with SAX and spits out
94 # This would print every latitude value:
96 # gpx = OSM::GPXImporter.new('somefile.gpx')
97 # gpx.points {|p| puts p['latitude']}
99 # FIXME swap REXML for libXML
100 attr_reader :possible_points
101 attr_reader :actual_points
102 attr_reader :tracksegs
116 date = DateTime.now();
123 parser = REXML::Parsers::SAX2Parser.new(@file)
125 parser.listen( :start_element, %w{ trkpt }) do |uri,localname,qname,attributes|
126 lat = attributes['lat'].to_f
127 lon = attributes['lon'].to_f
131 @possible_points += 1
134 parser.listen( :characters, %w{ ele } ) do |text|
139 parser.listen( :characters, %w{ time } ) do |text|
140 if text && text != ''
142 date = DateTime.parse(text)
149 parser.listen( :end_element, %w{ trkseg } ) do |uri, localname, qname|
153 parser.listen( :end_element, %w{ trkpt } ) do |uri,localname,qname|
154 if gotlatlon && gotdate
155 ele = '0' unless gotele
156 if lat < 90 && lat > -90 && lon > -180 && lon < 180
158 yield Hash['latitude' => lat, 'longitude' => lon, 'timestamp' => date, 'altitude' => ele, 'segment' => @tracksegs]
169 def get_picture(min_lat, min_lon, max_lat, max_lon, num_points)
170 #puts "getting picfor bbox #{min_lat},#{min_lon} - #{max_lat},#{max_lon}"
174 proj = OSM::Mercator.new(min_lat, min_lon, max_lat, max_lon, width, height)
176 linegc = Magick::Draw.new
177 linegc.stroke_linejoin('miter')
178 linegc.stroke_width(1)
179 linegc.stroke('#BBBBBB')
180 linegc.fill('#BBBBBB')
182 highlightgc = Magick::Draw.new
183 highlightgc.stroke_linejoin('miter')
184 highlightgc.stroke_width(3)
185 highlightgc.stroke('#000000')
186 highlightgc.fill('#000000')
191 image = Magick::Image.new(width, height) do |image|
192 image.background_color = 'white'
207 px = proj.x(p['longitude'])
208 py = proj.y(p['latitude'])
218 gc.line(px, py, oldpx, oldpy)
225 if m > num_points.to_f / frames.to_f * (mm+1)
233 il = Magick::ImageList.new
245 def get_icon(min_lat, min_lon, max_lat, max_lon)
246 #puts "getting icon for bbox #{min_lat},#{min_lon} - #{max_lat},#{max_lon}"
249 proj = OSM::Mercator.new(min_lat, min_lon, max_lat, max_lon, width, height)
251 gc = Magick::Draw.new
252 gc.stroke_linejoin('miter')
257 image = Magick::Image.new(width, height) do |image|
258 image.background_color = 'white'
268 px = proj.x(p['longitude'])
269 py = proj.y(p['latitude'])
271 gc.dup.line(px, py, oldpx, oldpy).draw(image) unless first
286 # initialise with a base position
287 def initialize(lat, lon)
288 @lat = lat * PI / 180
289 @lon = lon * PI / 180
292 # get the distance from the base position to a given position
293 def distance(lat, lon)
296 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
299 # get the worst case bounds for a given radius from the base position
301 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
302 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
303 minlat = (@lat - latradius) * 180 / PI
304 maxlat = (@lat + latradius) * 180 / PI
305 minlon = (@lon - lonradius) * 180 / PI
306 maxlon = (@lon + lonradius) * 180 / PI
307 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
312 def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
313 @doc = XML::Document.new
314 @doc.encoding = 'UTF-8'
316 rss = XML::Node.new 'rss'
318 rss['version'] = "2.0"
319 rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
320 @channel = XML::Node.new 'channel'
322 title = XML::Node.new 'title'
325 description_el = XML::Node.new 'description'
326 @channel << description_el
328 description_el << feed_description
329 link = XML::Node.new 'link'
332 image = XML::Node.new 'image'
334 url = XML::Node.new 'url'
335 url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
337 title = XML::Node.new 'title'
338 title << "OpenStreetMap"
340 width = XML::Node.new 'width'
343 height = XML::Node.new 'height'
346 link = XML::Node.new 'link'
351 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)
352 item = XML::Node.new 'item'
354 title = XML::Node.new 'title'
357 link = XML::Node.new 'link'
361 guid = XML::Node.new 'guid'
365 description = XML::Node.new 'description'
366 description << description_text
369 author = XML::Node.new 'author'
370 author << author_text
373 pubDate = XML::Node.new 'pubDate'
374 pubDate << timestamp.to_s(:rfc822)
378 lat_el = XML::Node.new 'geo:lat'
379 lat_el << latitude.to_s
384 lon_el = XML::Node.new 'geo:long'
385 lon_el << longitude.to_s
399 doc = XML::Document.new
400 doc.encoding = 'UTF-8'
401 root = XML::Node.new 'osm'
402 root['version'] = API_VERSION
403 root['generator'] = 'OpenStreetMap server'
409 def self.IPLocation(ip_address)
410 Timeout::timeout(4) do
411 Net::HTTP.start('api.hostip.info') do |http|
412 country = http.get("/country.php?ip=#{ip_address}").body
413 country = "GB" if country == "UK"
414 Net::HTTP.start('ws.geonames.org') do |http|
415 xml = REXML::Document.new(http.get("/countryInfo?country=#{country}").body)
416 xml.elements.each("geonames/country") do |ele|
417 minlon = ele.get_text("bBoxWest").to_s
418 minlat = ele.get_text("bBoxSouth").to_s
419 maxlon = ele.get_text("bBoxEast").to_s
420 maxlat = ele.get_text("bBoxNorth").to_s
421 return { :minlon => minlon, :minlat => minlat, :maxlon => maxlon, :maxlat => maxlat }
432 # Construct a random token of a given length
433 def self.make_token(length = 30)
434 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
438 token += chars[(rand * chars.length).to_i].chr
444 # Return an encrypted version of a password
445 def self.encrypt_password(password, salt)
446 return Digest::MD5.hexdigest(password) if salt.nil?
447 return Digest::MD5.hexdigest(salt + password)
450 # Return an SQL fragment to select a given area of the globe
451 def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
452 tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
453 minlat = (minlat * 10000000).round
454 minlon = (minlon * 10000000).round
455 maxlat = (maxlat * 10000000).round
456 maxlon = (maxlon * 10000000).round
458 return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"