1 class ApiController < ApplicationController
3 skip_before_filter :verify_authenticity_token
4 before_filter :check_api_readable, :except => [:capabilities]
5 after_filter :compress_output
6 around_filter :api_call_handle_error, :api_call_timeout
8 # Help methods for checking boundary sanity and area size
11 # Get an XML response containing a list of tracepoints that have been uploaded
12 # within the specified bounding box, and in the specified page.
14 #retrieve the page number
15 page = params['page'].to_s.to_i
18 report_error("Page number must be greater than or equal to 0")
22 offset = page * TRACEPOINTS_PER_PAGE
26 unless bbox and bbox.count(',') == 3
27 report_error("The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat")
31 bbox = bbox.split(',')
32 min_lon, min_lat, max_lon, max_lat = sanitise_boundaries(bbox)
33 # check boundary is sane and area within defined
34 # see /config/application.yml
36 check_boundaries(min_lon, min_lat, max_lon, max_lat)
37 rescue Exception => err
38 report_error(err.message)
43 points = Tracepoint.bbox(min_lat, min_lon, max_lat, max_lon).offset(offset).limit(TRACEPOINTS_PER_PAGE).order("gpx_id DESC, trackid ASC, timestamp ASC")
45 doc = XML::Document.new
46 doc.encoding = XML::Encoding::UTF_8
47 root = XML::Node.new 'gpx'
48 root['version'] = '1.0'
49 root['creator'] = 'OpenStreetMap.org'
50 root['xmlns'] = "http://www.topografix.com/GPX/1/0"
54 # initialise these variables outside of the loop so that they
55 # stay in scope and don't get free'd up by the GC during the
66 points.each do |point|
67 if gpx_id != point.gpx_id
70 gpx_file = Trace.find(gpx_id)
72 if gpx_file.trackable?
73 track = XML::Node.new 'trk'
77 if gpx_file.identifiable?
78 track << (XML::Node.new("name") << gpx_file.name)
79 track << (XML::Node.new("desc") << gpx_file.description)
80 track << (XML::Node.new("url") << url_for(:controller => 'trace', :action => 'view', :id => gpx_file.id))
83 # use the anonymous track segment if the user hasn't allowed
84 # their GPX points to be tracked.
87 anon_track = XML::Node.new 'trk'
88 doc.root << anon_track
94 if trackid != point.trackid
95 if gpx_file.trackable?
96 trkseg = XML::Node.new 'trkseg'
98 trackid = point.trackid
101 anon_trkseg = XML::Node.new 'trkseg'
102 anon_track << anon_trkseg
108 trkseg << point.to_xml_node(timestamps)
111 response.headers["Content-Disposition"] = "attachment; filename=\"tracks.gpx\""
113 render :text => doc.to_s, :content_type => "text/xml"
116 # This is probably the most common call of all. It is used for getting the
117 # OSM data for a specified bounding box, usually for editing. First the
118 # bounding box (bbox) is checked to make sure that it is sane. All nodes
119 # are searched, then all the ways that reference those nodes are found.
120 # All Nodes that are referenced by those ways are fetched and added to the list
122 # Then all the relations that reference the already found nodes and ways are
123 # fetched. All the nodes and ways that are referenced by those ways are then
124 # fetched. Finally all the xml is returned.
126 # Figure out the bbox
127 bbox = params['bbox']
129 unless bbox and bbox.count(',') == 3
130 # alternatively: report_error(TEXT['boundary_parameter_required']
131 report_error("The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat")
135 bbox = bbox.split(',')
137 min_lon, min_lat, max_lon, max_lat = sanitise_boundaries(bbox)
139 # check boundary is sane and area within defined
140 # see /config/application.yml
142 check_boundaries(min_lon, min_lat, max_lon, max_lat)
143 rescue Exception => err
144 report_error(err.message)
148 # FIXME um why is this area using a different order for the lat/lon from above???
149 @nodes = Node.bbox(min_lat, min_lon, max_lat, max_lon).where(:visible => true).includes(:node_tags).limit(MAX_NUMBER_OF_NODES+1)
150 # get all the nodes, by tag not yet working, waiting for change from NickB
151 # need to be @nodes (instance var) so tests in /spec can be performed
152 #@nodes = Node.search(bbox, params[:tag])
154 node_ids = @nodes.collect(&:id)
155 if node_ids.length > MAX_NUMBER_OF_NODES
156 report_error("You requested too many nodes (limit is #{MAX_NUMBER_OF_NODES}). Either request a smaller area, or use planet.osm")
159 if node_ids.length == 0
160 render :text => "<osm version='#{API_VERSION}' generator='#{GENERATOR}'></osm>", :content_type => "text/xml"
164 doc = OSM::API.new.get_xml_doc
167 bounds = XML::Node.new 'bounds'
168 bounds['minlat'] = min_lat.to_s
169 bounds['minlon'] = min_lon.to_s
170 bounds['maxlat'] = max_lat.to_s
171 bounds['maxlon'] = max_lon.to_s
175 # find which ways are needed
177 if node_ids.length > 0
178 way_nodes = WayNode.find_all_by_node_id(node_ids)
179 way_ids = way_nodes.collect { |way_node| way_node.id[0] }
180 ways = Way.find(way_ids, :include => [:way_nodes, :way_tags])
182 list_of_way_nodes = ways.collect { |way|
183 way.way_nodes.collect { |way_node| way_node.node_id }
185 list_of_way_nodes.flatten!
188 list_of_way_nodes = Array.new
191 # - [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
192 nodes_to_fetch = (list_of_way_nodes.uniq - node_ids) - [0]
194 if nodes_to_fetch.length > 0
195 @nodes += Node.includes(:node_tags).find(nodes_to_fetch)
200 user_display_name_cache = {}
202 @nodes.each do |node|
204 doc.root << node.to_xml_node(changeset_cache, user_display_name_cache)
205 visible_nodes[node.id] = node
212 doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache)
217 relations = Relation.nodes(visible_nodes.keys).visible +
218 Relation.ways(way_ids).visible
220 # we do not normally return the "other" partners referenced by an relation,
221 # e.g. if we return a way A that is referenced by relation X, and there's
222 # another way B also referenced, that is not returned. But we do make
223 # an exception for cases where an relation references another *relation*;
224 # in that case we return that as well (but we don't go recursive here)
225 relations += Relation.relations(relations.collect { |r| r.id }).visible
227 # this "uniq" may be slightly inefficient; it may be better to first collect and output
228 # all node-related relations, then find the *not yet covered* way-related ones etc.
229 relations.uniq.each do |relation|
230 doc.root << relation.to_xml_node(nil, changeset_cache, user_display_name_cache)
233 response.headers["Content-Disposition"] = "attachment; filename=\"map.osm\""
235 render :text => doc.to_s, :content_type => "text/xml"
238 # Get a list of the tiles that have changed within a specified time
241 zoom = (params[:zoom] || '12').to_i
243 if params.include?(:start) and params.include?(:end)
244 starttime = Time.parse(params[:start])
245 endtime = Time.parse(params[:end])
247 hours = (params[:hours] || '1').to_i.hours
248 endtime = Time.now.getutc
249 starttime = endtime - hours
252 if zoom >= 1 and zoom <= 16 and
253 endtime > starttime and endtime - starttime <= 24.hours
254 mask = (1 << zoom) - 1
256 tiles = Node.where(:timestamp => starttime .. endtime).group("maptile_for_point(latitude, longitude, #{zoom})").count
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"