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
15 # Raised when an API object is not found.
16 class APINotFoundError < APIError
19 # Raised when a precondition to an API action fails sanity check.
20 class APIPreconditionFailedError < APIError
23 # Raised when to delete an already-deleted object.
24 class APIAlreadyDeletedError < APIError
27 # Raised when the provided version is not equal to the latest in the db.
28 class APIVersionMismatchError < APIError
29 def initialize(provided, latest)
30 @provided, @latest = provided, latest
33 attr_reader :provided, :latest
36 # Helper methods for going to/from mercator and lat/lng.
40 #init me with your bounding box and the size of your image
41 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
42 xsize = xsheet(max_lon) - xsheet(min_lon)
43 ysize = ysheet(max_lat) - ysheet(min_lat)
44 xscale = xsize / width
45 yscale = ysize / height
46 scale = [xscale, yscale].max
48 xpad = width * scale - xsize
49 ypad = height * scale - ysize
54 @tx = xsheet(min_lon) - xpad / 2
55 @ty = ysheet(min_lat) - ypad / 2
57 @bx = xsheet(max_lon) + xpad / 2
58 @by = ysheet(max_lat) + ypad / 2
61 #the following two functions will give you the x/y on the entire sheet
64 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
71 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
74 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
78 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
83 # This piece of magic reads a GPX with SAX and spits out
86 # This would print every latitude value:
88 # gpx = OSM::GPXImporter.new('somefile.gpx')
89 # gpx.points {|p| puts p['latitude']}
91 # FIXME swap REXML for libXML
92 attr_reader :possible_points
93 attr_reader :actual_points
94 attr_reader :tracksegs
108 date = DateTime.now();
115 parser = REXML::Parsers::SAX2Parser.new(@file)
117 parser.listen( :start_element, %w{ trkpt }) do |uri,localname,qname,attributes|
118 lat = attributes['lat'].to_f
119 lon = attributes['lon'].to_f
123 @possible_points += 1
126 parser.listen( :characters, %w{ ele } ) do |text|
131 parser.listen( :characters, %w{ time } ) do |text|
132 if text && text != ''
134 date = DateTime.parse(text)
141 parser.listen( :end_element, %w{ trkseg } ) do |uri, localname, qname|
145 parser.listen( :end_element, %w{ trkpt } ) do |uri,localname,qname|
146 if gotlatlon && gotdate
147 ele = '0' unless gotele
148 if lat < 90 && lat > -90 && lon > -180 && lon < 180
150 yield Hash['latitude' => lat, 'longitude' => lon, 'timestamp' => date, 'altitude' => ele, 'segment' => @tracksegs]
161 def get_picture(min_lat, min_lon, max_lat, max_lon, num_points)
162 #puts "getting picfor bbox #{min_lat},#{min_lon} - #{max_lat},#{max_lon}"
166 proj = OSM::Mercator.new(min_lat, min_lon, max_lat, max_lon, width, height)
168 linegc = Magick::Draw.new
169 linegc.stroke_linejoin('miter')
170 linegc.stroke_width(1)
171 linegc.stroke('#BBBBBB')
172 linegc.fill('#BBBBBB')
174 highlightgc = Magick::Draw.new
175 highlightgc.stroke_linejoin('miter')
176 highlightgc.stroke_width(3)
177 highlightgc.stroke('#000000')
178 highlightgc.fill('#000000')
183 image = Magick::Image.new(width, height) do |image|
184 image.background_color = 'white'
199 px = proj.x(p['longitude'])
200 py = proj.y(p['latitude'])
210 gc.line(px, py, oldpx, oldpy)
217 if m > num_points.to_f / frames.to_f * (mm+1)
225 il = Magick::ImageList.new
237 def get_icon(min_lat, min_lon, max_lat, max_lon)
238 #puts "getting icon for bbox #{min_lat},#{min_lon} - #{max_lat},#{max_lon}"
241 proj = OSM::Mercator.new(min_lat, min_lon, max_lat, max_lon, width, height)
243 gc = Magick::Draw.new
244 gc.stroke_linejoin('miter')
249 image = Magick::Image.new(width, height) do |image|
250 image.background_color = 'white'
260 px = proj.x(p['longitude'])
261 py = proj.y(p['latitude'])
263 gc.dup.line(px, py, oldpx, oldpy).draw(image) unless first
278 # initialise with a base position
279 def initialize(lat, lon)
280 @lat = lat * PI / 180
281 @lon = lon * PI / 180
284 # get the distance from the base position to a given position
285 def distance(lat, lon)
288 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
291 # get the worst case bounds for a given radius from the base position
293 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
294 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
295 minlat = (@lat - latradius) * 180 / PI
296 maxlat = (@lat + latradius) * 180 / PI
297 minlon = (@lon - lonradius) * 180 / PI
298 maxlon = (@lon + lonradius) * 180 / PI
299 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
304 def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
305 @doc = XML::Document.new
306 @doc.encoding = 'UTF-8'
308 rss = XML::Node.new 'rss'
310 rss['version'] = "2.0"
311 rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
312 @channel = XML::Node.new 'channel'
314 title = XML::Node.new 'title'
317 description_el = XML::Node.new 'description'
318 @channel << description_el
320 description_el << feed_description
321 link = XML::Node.new 'link'
324 image = XML::Node.new 'image'
326 url = XML::Node.new 'url'
327 url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
329 title = XML::Node.new 'title'
330 title << "OpenStreetMap"
332 width = XML::Node.new 'width'
335 height = XML::Node.new 'height'
338 link = XML::Node.new 'link'
343 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)
344 item = XML::Node.new 'item'
346 title = XML::Node.new 'title'
349 link = XML::Node.new 'link'
353 guid = XML::Node.new 'guid'
357 description = XML::Node.new 'description'
358 description << description_text
361 author = XML::Node.new 'author'
362 author << author_text
365 pubDate = XML::Node.new 'pubDate'
366 pubDate << timestamp.to_s(:rfc822)
370 lat_el = XML::Node.new 'geo:lat'
371 lat_el << latitude.to_s
376 lon_el = XML::Node.new 'geo:long'
377 lon_el << longitude.to_s
391 doc = XML::Document.new
392 doc.encoding = 'UTF-8'
393 root = XML::Node.new 'osm'
394 root['version'] = API_VERSION
395 root['generator'] = 'OpenStreetMap server'
401 def self.IPLocation(ip_address)
402 Timeout::timeout(4) do
403 Net::HTTP.start('api.hostip.info') do |http|
404 country = http.get("/country.php?ip=#{ip_address}").body
405 country = "GB" if country == "UK"
406 Net::HTTP.start('ws.geonames.org') do |http|
407 xml = REXML::Document.new(http.get("/countryInfo?country=#{country}").body)
408 xml.elements.each("geonames/country") do |ele|
409 minlon = ele.get_text("bBoxWest").to_s
410 minlat = ele.get_text("bBoxSouth").to_s
411 maxlon = ele.get_text("bBoxEast").to_s
412 maxlat = ele.get_text("bBoxNorth").to_s
413 return { :minlon => minlon, :minlat => minlat, :maxlon => maxlon, :maxlat => maxlat }
424 # Construct a random token of a given length
425 def self.make_token(length = 30)
426 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
430 token += chars[(rand * chars.length).to_i].chr
436 # Return an encrypted version of a password
437 def self.encrypt_password(password, salt)
438 return Digest::MD5.hexdigest(password) if salt.nil?
439 return Digest::MD5.hexdigest(salt + password)
442 # Return an SQL fragment to select a given area of the globe
443 def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
444 tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
445 minlat = (minlat * 10000000).round
446 minlon = (minlon * 10000000).round
447 maxlat = (maxlat * 10000000).round
448 maxlon = (maxlon * 10000000).round
450 return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"