OpenStreetMap has an API called Overpass that lets you access OSM data dynamically. In this recipe, we'll add some OSM tourism points of interest to a map.
You will need to use the QGIS Plugin Manager to install the Quick OSM plugin.
You will also need to download the following shapefile and unzip it to your qgis_data/ms
directory:
We will load our base layer that defines the area of interest. Then, we'll use the Processing Toolbox to build a query for OSM, download the data, and add it to the map. To do this, we need to perform the following steps:
processing
module:import processing
lyr = QgsVectorLayer("/qgis_data/ms/MSCoast_geo.shp", "MS Coast", "ogr")
ext = lyr.extent() w = ext.xMinimum() s = ext.yMinimum() e = ext.xMaximum() n = ext.yMaximum()
factory = processing.runalg("quickosm:queryfactory", "tourism","","%s,%s,%s,%s" % (w,e,s,n),"",25) q = factory["OUTPUT_QUERY"]
bbox_query = """<bbox-query e="%s" n="%s" s="%s" w="%s"/>""" % (e,n,s,w) bad_xml = """<bbox-query %s,%s,%s,%s/>""" % (w,e,s,n) good_query = q.replace(bad_xml, bbox_query)
results = processing.runalg("quickosm:queryoverpassapiwithastring","http://overpass-api.de/api/",good_query,"0,0,0,0","",None) osm = results["OUTPUT_FILE"]
poly = "/qgis_data/ms/tourism_poly.shp" multiline = "/qgis_data/ms/tourism_multil.shp" line = "/qgis_data/ms/tourism_lines.shp" points = "/qgis_data/ms/tourism_points.shp"
processing.runalg("quickosm:ogrdefault",osm,"","","","",poly,multiline,line,points)
tourism_points = QgsVectorLayer(points, "Points of Interest", "ogr")
QgsMapLayerRegistry.instance().addMapLayers([tourism_points, lyr]
The Quick OSM plugin manages the Overpass API. What's interesting about this plugin is that it provides processing algorithms in addition to a GUI interface. The processing algorithm that creates the query unfortunately formats the bbox-query
tag improperly, so we need to work around this issue with the string replace. The API returns an OSM XML file that we must convert to shapefiles for use in QGIS.