]> git.openstreetmap.org Git - rails.git/blob - lib/osm.rb
Move common support code from the base migration to a library file where
[rails.git] / lib / osm.rb
1 module OSM
2
3   # This piece of magic reads a GPX with SAX and spits out
4   # lat/lng and stuff
5   #
6   # This would print every latitude value:
7   #
8   # gpx = OSM:GPXImporter.new('somefile.gpx')
9   # gpx.points {|p| puts p['latitude']}
10
11   require 'time'
12   require 'rexml/parsers/sax2parser'
13   require 'rexml/text'
14   require 'xml/libxml'
15   require 'RMagick'
16
17   class Mercator
18     include Math
19
20     def initialize(lat, lon, degrees_per_pixel, width, height)
21       #init me with your centre lat/lon, the number of degrees per pixel and the size of your image
22       @clat = lat
23       @clon = lon
24       @degrees_per_pixel = degrees_per_pixel
25       @degrees_per_pixel = 0.0000000001 if @degrees_per_pixel < 0.0000000001
26       @width = width
27       @height = height
28       @dlon = width / 2 * @degrees_per_pixel
29       @dlat = height / 2 * @degrees_per_pixel  * cos(@clat * PI / 180)
30
31       @tx = xsheet(@clon - @dlon)
32       @ty = ysheet(@clat - @dlat)
33
34       @bx = xsheet(@clon + @dlon)
35       @by = ysheet(@clat + @dlat)
36
37     end
38
39     #the following two functions will give you the x/y on the entire sheet
40
41     def kilometerinpixels
42       return 40008.0  / 360.0 * @degrees_per_pixel
43     end
44
45     def ysheet(lat)
46       log(tan(PI / 4 +  (lat  * PI / 180 / 2)))
47     end
48
49     def xsheet(lon)
50       lon
51     end
52
53     #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
54
55     def y(lat)
56       return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
57     end
58
59     def x(lon)
60       return  ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
61     end
62   end
63
64
65   class GPXImporter
66     # FIXME swap REXML for libXML
67     attr_reader :possible_points
68     attr_reader :actual_points
69     attr_reader :tracksegs
70
71     def initialize(filename)
72       @filename = filename
73     end
74
75     def points
76       @possible_points = 0
77       @actual_points = 0
78       @tracksegs = 0
79
80       lat = -1
81       lon = -1
82       ele = -1
83       date = DateTime.now();
84       gotlatlon = false
85       gotele = false
86       gotdate = false
87
88       parser = REXML::Parsers::SAX2Parser.new(File.new(@filename))
89
90       parser.listen( :start_element,  %w{ trkpt }) do |uri,localname,qname,attributes| 
91         lat = attributes['lat'].to_f
92         lon = attributes['lon'].to_f
93         gotlatlon = true
94         @possible_points += 1
95       end
96
97       parser.listen( :characters, %w{ ele } ) do |text|
98         ele = text
99         gotele = true
100       end
101
102       parser.listen( :characters, %w{ time } ) do |text|
103         if text && text != ''
104           date = DateTime.parse(text)
105           gotdate = true
106         end
107       end
108
109       parser.listen( :end_element, %w{ trkseg } ) do |uri, localname, qname|
110         @tracksegs += 1
111       end
112
113       parser.listen( :end_element, %w{ trkpt } ) do |uri,localname,qname|
114         if gotlatlon && gotdate
115           ele = '0' unless gotele
116           if lat < 90 && lat > -90 && lon > -180 && lon < 180
117             @actual_points += 1
118             yield Hash['latitude' => lat, 'longitude' => lon, 'timestamp' => date, 'altitude' => ele, 'segment' => @tracksegs]
119           end
120         end
121         gotlatlon = false
122         gotele = false
123         gotdate = false
124       end
125
126       parser.parse
127     end
128
129     def get_picture(min_lat, min_lon, max_lat, max_lon, num_points)
130       #puts "getting picfor bbox #{min_lat},#{min_lon} - #{max_lat},#{max_lon}"
131       frames = 10
132       width = 250
133       height = 250
134       rat= Math.cos( ((max_lat + min_lat)/2.0) /  180.0 * 3.141592)
135       proj = OSM::Mercator.new((min_lat + max_lat) / 2, (max_lon + min_lon) / 2, (max_lat - min_lat) / width / rat, width, height)
136
137       images = []
138
139       frames.times do
140         gc =  Magick::Draw.new
141         gc.stroke_linejoin('miter')
142         gc.stroke('#FFFFFF')
143         gc.fill('#FFFFFF')
144         gc.rectangle(0,0,width,height)
145         gc.stroke_width(1)
146         images << gc
147       end
148
149       oldpx = 0.0
150       oldpy = 0.0
151
152       first = true
153
154       m = 0
155       mm = 0
156       points do |p|
157         px = proj.x(p['longitude'])
158         py = proj.y(p['latitude'])
159         frames.times do |n|
160           images[n].stroke_width(1)
161           images[n].stroke('#BBBBBB')
162           images[n].fill('#BBBBBB')
163         #  puts "A #{px},#{py} - #{oldpx},#{oldpy}"
164           images[n].line(px, py, oldpx, oldpy ) unless first
165         end
166         images[mm].stroke_width(3)
167         images[mm].stroke('#000000')
168         images[mm].fill('#000000')
169         images[mm].line(px, py, oldpx, oldpy ) unless first
170       #  puts "B #{px},#{py} - #{oldpx},#{oldpy}"
171         m +=1
172         if m > num_points.to_f / frames.to_f * (mm+1)
173           mm += 1
174         end
175         first = false
176         oldpy = py
177         oldpx = px
178       end
179
180       il = Magick::ImageList.new
181
182       frames.times do |n|
183         canvas = Magick::Image.new(width, height) {
184           self.background_color = 'white'
185         }
186         begin
187           images[n].draw(canvas)
188         rescue ArgumentError
189         end
190         canvas.format = 'GIF'
191         il << canvas
192       end
193
194       il.delay = 50
195       il.format = 'GIF'
196       return il.to_blob
197     end
198
199     def get_icon(min_lat, min_lon, max_lat, max_lon)
200       #puts "getting icon for bbox #{min_lat},#{min_lon} - #{max_lat},#{max_lon}"
201       width = 50
202       height = 50
203       rat= Math.cos( ((max_lat + min_lat)/2.0) /  180.0 * 3.141592)
204       proj = OSM::Mercator.new((min_lat + max_lat) / 2, (max_lon + min_lon) / 2, (max_lat - min_lat) / width / rat, width, height)
205
206       images = []
207
208       gc =  Magick::Draw.new
209       gc.stroke_linejoin('miter')
210
211       oldpx = 0.0
212       oldpy = 0.0
213
214       first = true
215
216       gc.stroke_width(1)
217       gc.stroke('#000000')
218       gc.fill('#000000')
219
220       points do |p|
221         px = proj.x(p['longitude'])
222         py = proj.y(p['latitude'])
223         gc.line(px, py, oldpx, oldpy ) unless first
224        # puts "C #{px},#{py} - #{oldpx},#{oldpy}"
225         first = false
226         oldpy = py
227         oldpx = px
228       end
229
230       canvas = Magick::Image.new(width, height) {
231         self.background_color = 'white'
232       }
233       begin
234         gc.draw(canvas)
235       rescue ArgumentError
236       end
237       canvas.format = 'GIF'
238       return canvas.to_blob
239     end
240
241   end
242
243   class GreatCircle
244     include Math
245
246     # initialise with a base position
247     def initialize(lat, lon)
248       @lat = lat * PI / 180
249       @lon = lon * PI / 180
250     end
251
252     # get the distance from the base position to a given position
253     def distance(lat, lon)
254       lat = lat * PI / 180
255       lon = lon * PI / 180
256       return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
257     end
258
259     # get the worst case bounds for a given radius from the base position
260     def bounds(radius)
261       latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
262       lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
263       minlat = (@lat - latradius) * 180 / PI
264       maxlat = (@lat + latradius) * 180 / PI
265       minlon = (@lon - lonradius) * 180 / PI
266       maxlon = (@lon + lonradius) * 180 / PI
267       return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
268     end
269   end
270
271   class GeoRSS
272     def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
273       @doc = XML::Document.new
274       @doc.encoding = 'UTF-8' 
275       
276       rss = XML::Node.new 'rss'
277       @doc.root = rss
278       rss['version'] = "2.0"
279       rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
280       @channel = XML::Node.new 'channel'
281       rss << @channel
282       title = XML::Node.new 'title'
283       title <<  feed_title
284       @channel << title
285       description_el = XML::Node.new 'description'
286       @channel << description_el
287
288       description_el << feed_description
289       link = XML::Node.new 'link'
290       link << feed_url
291       @channel << link
292       image = XML::Node.new 'image'
293       @channel << image
294       url = XML::Node.new 'url'
295       url << 'http://www.openstreetmap.org/feeds/mag_map-rss2.0.png'
296       image << url
297       title = XML::Node.new 'title'
298       title << "OpenStreetMap"
299       image << title
300       width = XML::Node.new 'width'
301       width << '100'
302       image << width
303       height = XML::Node.new 'height'
304       height << '100'
305       image << height
306       link = XML::Node.new 'link'
307       link << feed_url
308       image << link
309     end
310
311     def add(latitude=0, longitude=0, title_text='dummy title', url='http://www.example.com/', description_text='dummy description', timestamp=DateTime.now)
312       item = XML::Node.new 'item'
313
314       title = XML::Node.new 'title'
315       item << title
316       title << title_text
317       link = XML::Node.new 'link'
318       link << url
319       item << link
320
321       guid = XML::Node.new 'guid'
322       guid << url
323       item << guid
324
325       description = XML::Node.new 'description'
326       description << description_text
327       item << description
328
329       pubDate = XML::Node.new 'pubDate'
330       pubDate << timestamp.to_s(:rfc822)
331       item << pubDate
332
333       if latitude
334         lat_el = XML::Node.new 'geo:lat'
335         lat_el << latitude.to_s
336         item << lat_el
337       end
338
339       if longitude
340         lon_el = XML::Node.new 'geo:long'
341         lon_el << longitude.to_s
342         item << lon_el
343       end
344
345       @channel << item
346     end
347
348     def to_s
349       return @doc.to_s
350     end
351   end
352
353   class API
354     def get_xml_doc
355       doc = XML::Document.new
356       doc.encoding = 'UTF-8' 
357       root = XML::Node.new 'osm'
358       root['version'] = API_VERSION
359       root['generator'] = 'OpenStreetMap server'
360       doc.root = root
361       return doc
362     end
363   end
364 end