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 # Helper methods for going to/from mercator and lat/lng.
31 #init me with your bounding box and the size of your image
32 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
33 xsize = xsheet(max_lon) - xsheet(min_lon)
34 ysize = ysheet(max_lat) - ysheet(min_lat)
35 xscale = xsize / width
36 yscale = ysize / height
37 scale = [xscale, yscale].max
39 xpad = width * scale - xsize
40 ypad = height * scale - ysize
45 @tx = xsheet(min_lon) - xpad / 2
46 @ty = ysheet(min_lat) - ypad / 2
48 @bx = xsheet(max_lon) + xpad / 2
49 @by = ysheet(max_lat) + ypad / 2
52 #the following two functions will give you the x/y on the entire sheet
55 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
62 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
65 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
69 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
74 # This piece of magic reads a GPX with SAX and spits out
77 # This would print every latitude value:
79 # gpx = OSM::GPXImporter.new('somefile.gpx')
80 # gpx.points {|p| puts p['latitude']}
82 # FIXME swap REXML for libXML
83 attr_reader :possible_points
84 attr_reader :actual_points
85 attr_reader :tracksegs
99 date = DateTime.now();
106 parser = REXML::Parsers::SAX2Parser.new(@file)
108 parser.listen( :start_element, %w{ trkpt }) do |uri,localname,qname,attributes|
109 lat = attributes['lat'].to_f
110 lon = attributes['lon'].to_f
114 @possible_points += 1
117 parser.listen( :characters, %w{ ele } ) do |text|
122 parser.listen( :characters, %w{ time } ) do |text|
123 if text && text != ''
125 date = DateTime.parse(text)
132 parser.listen( :end_element, %w{ trkseg } ) do |uri, localname, qname|
136 parser.listen( :end_element, %w{ trkpt } ) do |uri,localname,qname|
137 if gotlatlon && gotdate
138 ele = '0' unless gotele
139 if lat < 90 && lat > -90 && lon > -180 && lon < 180
141 yield Hash['latitude' => lat, 'longitude' => lon, 'timestamp' => date, 'altitude' => ele, 'segment' => @tracksegs]
152 def get_picture(min_lat, min_lon, max_lat, max_lon, num_points)
153 #puts "getting picfor bbox #{min_lat},#{min_lon} - #{max_lat},#{max_lon}"
157 proj = OSM::Mercator.new(min_lat, min_lon, max_lat, max_lon, width, height)
159 linegc = Magick::Draw.new
160 linegc.stroke_linejoin('miter')
161 linegc.stroke_width(1)
162 linegc.stroke('#BBBBBB')
163 linegc.fill('#BBBBBB')
165 highlightgc = Magick::Draw.new
166 highlightgc.stroke_linejoin('miter')
167 highlightgc.stroke_width(3)
168 highlightgc.stroke('#000000')
169 highlightgc.fill('#000000')
174 image = Magick::Image.new(width, height) do |image|
175 image.background_color = 'white'
190 px = proj.x(p['longitude'])
191 py = proj.y(p['latitude'])
201 gc.line(px, py, oldpx, oldpy)
208 if m > num_points.to_f / frames.to_f * (mm+1)
216 il = Magick::ImageList.new
228 def get_icon(min_lat, min_lon, max_lat, max_lon)
229 #puts "getting icon for bbox #{min_lat},#{min_lon} - #{max_lat},#{max_lon}"
232 proj = OSM::Mercator.new(min_lat, min_lon, max_lat, max_lon, width, height)
234 gc = Magick::Draw.new
235 gc.stroke_linejoin('miter')
240 image = Magick::Image.new(width, height) do |image|
241 image.background_color = 'white'
251 px = proj.x(p['longitude'])
252 py = proj.y(p['latitude'])
254 gc.dup.line(px, py, oldpx, oldpy).draw(image) unless first
269 # initialise with a base position
270 def initialize(lat, lon)
271 @lat = lat * PI / 180
272 @lon = lon * PI / 180
275 # get the distance from the base position to a given position
276 def distance(lat, lon)
279 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
282 # get the worst case bounds for a given radius from the base position
284 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
285 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
286 minlat = (@lat - latradius) * 180 / PI
287 maxlat = (@lat + latradius) * 180 / PI
288 minlon = (@lon - lonradius) * 180 / PI
289 maxlon = (@lon + lonradius) * 180 / PI
290 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
295 def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
296 @doc = XML::Document.new
297 @doc.encoding = 'UTF-8'
299 rss = XML::Node.new 'rss'
301 rss['version'] = "2.0"
302 rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
303 @channel = XML::Node.new 'channel'
305 title = XML::Node.new 'title'
308 description_el = XML::Node.new 'description'
309 @channel << description_el
311 description_el << feed_description
312 link = XML::Node.new 'link'
315 image = XML::Node.new 'image'
317 url = XML::Node.new 'url'
318 url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
320 title = XML::Node.new 'title'
321 title << "OpenStreetMap"
323 width = XML::Node.new 'width'
326 height = XML::Node.new 'height'
329 link = XML::Node.new 'link'
334 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)
335 item = XML::Node.new 'item'
337 title = XML::Node.new 'title'
340 link = XML::Node.new 'link'
344 guid = XML::Node.new 'guid'
348 description = XML::Node.new 'description'
349 description << description_text
352 author = XML::Node.new 'author'
353 author << author_text
356 pubDate = XML::Node.new 'pubDate'
357 pubDate << timestamp.to_s(:rfc822)
361 lat_el = XML::Node.new 'geo:lat'
362 lat_el << latitude.to_s
367 lon_el = XML::Node.new 'geo:long'
368 lon_el << longitude.to_s
382 doc = XML::Document.new
383 doc.encoding = 'UTF-8'
384 root = XML::Node.new 'osm'
385 root['version'] = API_VERSION
386 root['generator'] = 'OpenStreetMap server'
392 def self.IPLocation(ip_address)
393 Timeout::timeout(4) do
394 Net::HTTP.start('api.hostip.info') do |http|
395 country = http.get("/country.php?ip=#{ip_address}").body
396 country = "GB" if country == "UK"
397 Net::HTTP.start('ws.geonames.org') do |http|
398 xml = REXML::Document.new(http.get("/countryInfo?country=#{country}").body)
399 xml.elements.each("geonames/country") do |ele|
400 minlon = ele.get_text("bBoxWest").to_s
401 minlat = ele.get_text("bBoxSouth").to_s
402 maxlon = ele.get_text("bBoxEast").to_s
403 maxlat = ele.get_text("bBoxNorth").to_s
404 return { :minlon => minlon, :minlat => minlat, :maxlon => maxlon, :maxlat => maxlat }
415 # Construct a random token of a given length
416 def self.make_token(length = 30)
417 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
421 token += chars[(rand * chars.length).to_i].chr
427 # Return an encrypted version of a password
428 def self.encrypt_password(password, salt)
429 return Digest::MD5.hexdigest(password) if salt.nil?
430 return Digest::MD5.hexdigest(salt + password)
433 # Return an SQL fragment to select a given area of the globe
434 def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
435 tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
436 minlat = (minlat * 10000000).round
437 minlon = (minlon * 10000000).round
438 maxlat = (maxlat * 10000000).round
439 maxlon = (maxlon * 10000000).round
441 return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"