Getting vector data from OpenStreetMap

Let’s say that we need the Barcelona’s subway lines in geojson for our project, and we decided to use OpenStreetMap data. There is plenty of ways for getting OSM data, the most common is using their API, or the  geofabrik download page,  but this time we gonna use metro-extracts from mapzen.

We look for Barcelona. There is a lot of file formats there:

metro-extracts-barcelona

metro-extracts-barcelona

The file formats, as read from left to right, goes from the rawest form available to the most structured, prepackaged format. We can download directly the shapefile (but there is no fun with that, right?) so we go for the .pbf format

PBF – Protocolbuffer Binary Format. Highly compressed, intended as an alternative to the XML format

The downloaded file is called: barcelona_spain.osm.pbf but we need to convert it into a SpatiaLite database (which is an SQLite extension)  to be able to open it in QGIS. I’m in windows and have installed the OSGeo4W tools, so I’ll use the ogr2ogr command in the OSGeo shell.

Once in the command line, navegate to the directory where you have the file, in my case C:\spatialData>

and run this command to convert the .pbf file to a Spatial lite Data Base (bcnOSM.db):

ogr2ogr -f "SQLite" -dsco SPATIALITE=YES bcnOSM.db barcelona_spain.osm.pbf

In QGIS connect to the SQLite Data Base, search for the bcnOSM.db file, connect to the DB and add the multilinestrings table:

Once you have the data on QGIS right-click the layer and select Open Attribute Table, and use Select features using an expression. The simplier one is use:  ”name”  like ‘L%’,  with this you’ll select all subway lines (L1, L2….) and a couple of streets that have an L that you can remove from selection later.

Then save selection as shape, because before exporting to geojson we may want to edit the columns (as they will be properties fields in our geojson file). In this example I added a new column called “stroke”, that later we’ll use to set the color of the subway line. In the Attribute Table there is a column called other_tags that include the color in hexadecimal value. That is what we’ll use for the stroke value, like in the image.

Now we export to geojson and that’s it  :)

In case you want to use this file for your project you can download it here:

http://mappingandco.github.io/geojsonDB/barcelona/subway.geojson

Or, as we said on the previous post,  use it directly on your map:

var subwayURL = "http://mappingandco.github.io/geojsonDB/barcelona/subway.geojson"

$.getJSON(subwayURL, function(response) {
    var geojsonLayer = new L.GeoJSON(response);
    geojsonLayer.addTo(map);    
});