1 class ApiController < ApplicationController
3 before_filter :check_api_readable, :except => [:capabilities]
4 after_filter :compress_output
5 around_filter :api_call_handle_error, :api_call_timeout
7 # Help methods for checking boundary sanity and area size
10 # Get an XML response containing a list of tracepoints that have been uploaded
11 # within the specified bounding box, and in the specified page.
13 #retrieve the page number
14 page = params['page'].to_s.to_i
17 report_error("Page number must be greater than or equal to 0")
21 offset = page * TRACEPOINTS_PER_PAGE
25 unless bbox and bbox.count(',') == 3
26 report_error("The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat")
30 bbox = bbox.split(',')
31 min_lon, min_lat, max_lon, max_lat = sanitise_boundaries(bbox)
32 # check boundary is sane and area within defined
33 # see /config/application.yml
35 check_boundaries(min_lon, min_lat, max_lon, max_lat)
36 rescue Exception => err
37 report_error(err.message)
42 points = Tracepoint.find_by_area(min_lat, min_lon, max_lat, max_lon, :offset => offset, :limit => TRACEPOINTS_PER_PAGE, :order => "gpx_id DESC, trackid ASC, timestamp ASC" )
44 doc = XML::Document.new
45 doc.encoding = XML::Encoding::UTF_8
46 root = XML::Node.new 'gpx'
47 root['version'] = '1.0'
48 root['creator'] = 'OpenStreetMap.org'
49 root['xmlns'] = "http://www.topografix.com/GPX/1/0/"
53 # initialise these variables outside of the loop so that they
54 # stay in scope and don't get free'd up by the GC during the
65 points.each do |point|
66 if gpx_id != point.gpx_id
69 gpx_file = Trace.find(gpx_id)
71 if gpx_file.trackable?
72 track = XML::Node.new 'trk'
76 if gpx_file.identifiable?
77 track << (XML::Node.new("name") << gpx_file.name)
78 track << (XML::Node.new("desc") << gpx_file.description)
79 track << (XML::Node.new("url") << url_for(:controller => 'trace', :action => 'view', :id => gpx_file.id))
82 # use the anonymous track segment if the user hasn't allowed
83 # their GPX points to be tracked.
86 anon_track = XML::Node.new 'trk'
87 doc.root << anon_track
93 if trackid != point.trackid
94 if gpx_file.trackable?
95 trkseg = XML::Node.new 'trkseg'
97 trackid = point.trackid
100 anon_trkseg = XML::Node.new 'trkseg'
101 anon_track << anon_trkseg
107 trkseg << point.to_xml_node(timestamps)
110 response.headers["Content-Disposition"] = "attachment; filename=\"tracks.gpx\""
112 render :text => doc.to_s, :content_type => "text/xml"
115 # This is probably the most common call of all. It is used for getting the
116 # OSM data for a specified bounding box, usually for editing. First the
117 # bounding box (bbox) is checked to make sure that it is sane. All nodes
118 # are searched, then all the ways that reference those nodes are found.
119 # All Nodes that are referenced by those ways are fetched and added to the list
121 # Then all the relations that reference the already found nodes and ways are
122 # fetched. All the nodes and ways that are referenced by those ways are then
123 # fetched. Finally all the xml is returned.
125 # Figure out the bbox
126 bbox = params['bbox']
128 unless bbox and bbox.count(',') == 3
129 # alternatively: report_error(TEXT['boundary_parameter_required']
130 report_error("The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat")
134 bbox = bbox.split(',')
136 min_lon, min_lat, max_lon, max_lat = sanitise_boundaries(bbox)
138 # check boundary is sane and area within defined
139 # see /config/application.yml
141 check_boundaries(min_lon, min_lat, max_lon, max_lat)
142 rescue Exception => err
143 report_error(err.message)
147 # FIXME um why is this area using a different order for the lat/lon from above???
148 @nodes = Node.find_by_area(min_lat, min_lon, max_lat, max_lon, :conditions => {:visible => true}, :include => :node_tags, :limit => MAX_NUMBER_OF_NODES+1)
149 # get all the nodes, by tag not yet working, waiting for change from NickB
150 # need to be @nodes (instance var) so tests in /spec can be performed
151 #@nodes = Node.search(bbox, params[:tag])
153 node_ids = @nodes.collect(&:id)
154 if node_ids.length > MAX_NUMBER_OF_NODES
155 report_error("You requested too many nodes (limit is #{MAX_NUMBER_OF_NODES}). Either request a smaller area, or use planet.osm")
158 if node_ids.length == 0
159 render :text => "<osm version='#{API_VERSION}' generator='#{GENERATOR}'></osm>", :content_type => "text/xml"
163 doc = OSM::API.new.get_xml_doc
166 bounds = XML::Node.new 'bounds'
167 bounds['minlat'] = min_lat.to_s
168 bounds['minlon'] = min_lon.to_s
169 bounds['maxlat'] = max_lat.to_s
170 bounds['maxlon'] = max_lon.to_s
174 # find which ways are needed
176 if node_ids.length > 0
177 way_nodes = WayNode.find_all_by_node_id(node_ids)
178 way_ids = way_nodes.collect { |way_node| way_node.id[0] }
179 ways = Way.find(way_ids, :include => [:way_nodes, :way_tags])
181 list_of_way_nodes = ways.collect { |way|
182 way.way_nodes.collect { |way_node| way_node.node_id }
184 list_of_way_nodes.flatten!
187 list_of_way_nodes = Array.new
190 # - [0] in case some thing links to node 0 which doesn't exist. Shouldn't actually ever happen but it does. FIXME: file a ticket for this
191 nodes_to_fetch = (list_of_way_nodes.uniq - node_ids) - [0]
193 if nodes_to_fetch.length > 0
194 @nodes += Node.find(nodes_to_fetch, :include => :node_tags)
199 user_display_name_cache = {}
201 @nodes.each do |node|
203 doc.root << node.to_xml_node(changeset_cache, user_display_name_cache)
204 visible_nodes[node.id] = node
211 doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache)
216 relations = Relation.find_for_nodes(visible_nodes.keys, :conditions => {:visible => true}) +
217 Relation.find_for_ways(way_ids, :conditions => {:visible => true})
219 # we do not normally return the "other" partners referenced by an relation,
220 # e.g. if we return a way A that is referenced by relation X, and there's
221 # another way B also referenced, that is not returned. But we do make
222 # an exception for cases where an relation references another *relation*;
223 # in that case we return that as well (but we don't go recursive here)
224 relations += Relation.find_for_relations(relations.collect { |r| r.id }, :conditions => {:visible => true})
226 # this "uniq" may be slightly inefficient; it may be better to first collect and output
227 # all node-related relations, then find the *not yet covered* way-related ones etc.
228 relations.uniq.each do |relation|
229 doc.root << relation.to_xml_node(nil, changeset_cache, user_display_name_cache)
232 response.headers["Content-Disposition"] = "attachment; filename=\"map.osm\""
234 render :text => doc.to_s, :content_type => "text/xml"
237 # Get a list of the tiles that have changed within a specified time
240 zoom = (params[:zoom] || '12').to_i
242 if params.include?(:start) and params.include?(:end)
243 starttime = Time.parse(params[:start])
244 endtime = Time.parse(params[:end])
246 hours = (params[:hours] || '1').to_i.hours
247 endtime = Time.now.getutc
248 starttime = endtime - hours
251 if zoom >= 1 and zoom <= 16 and
252 endtime > starttime and endtime - starttime <= 24.hours
253 mask = (1 << zoom) - 1
255 tiles = Node.count(:conditions => ["timestamp BETWEEN ? AND ?", starttime, endtime],
256 :group => "maptile_for_point(latitude, longitude, #{zoom})")
258 doc = OSM::API.new.get_xml_doc
259 changes = XML::Node.new 'changes'
260 changes["starttime"] = starttime.xmlschema
261 changes["endtime"] = endtime.xmlschema
263 tiles.each do |tile, count|
264 x = (tile.to_i >> zoom) & mask
267 t = XML::Node.new 'tile'
271 t["changes"] = count.to_s
278 render :text => doc.to_s, :content_type => "text/xml"
280 render :text => "Requested zoom is invalid, or the supplied start is after the end time, or the start duration is more than 24 hours", :status => :bad_request
284 # External apps that use the api are able to query the api to find out some
285 # parameters of the API. It currently returns:
286 # * minimum and maximum API versions that can be used.
287 # * maximum area that can be requested in a bbox request in square degrees
288 # * number of tracepoints that are returned in each tracepoints page
290 doc = OSM::API.new.get_xml_doc
292 api = XML::Node.new 'api'
293 version = XML::Node.new 'version'
294 version['minimum'] = "#{API_VERSION}";
295 version['maximum'] = "#{API_VERSION}";
297 area = XML::Node.new 'area'
298 area['maximum'] = MAX_REQUEST_AREA.to_s;
300 tracepoints = XML::Node.new 'tracepoints'
301 tracepoints['per_page'] = TRACEPOINTS_PER_PAGE.to_s
303 waynodes = XML::Node.new 'waynodes'
304 waynodes['maximum'] = MAX_NUMBER_OF_WAY_NODES.to_s
306 changesets = XML::Node.new 'changesets'
307 changesets['maximum_elements'] = Changeset::MAX_ELEMENTS.to_s
309 timeout = XML::Node.new 'timeout'
310 timeout['seconds'] = API_TIMEOUT.to_s
315 render :text => doc.to_s, :content_type => "text/xml"