Use Overpass API to get OSM data

Overpass API

Have you ever needed very specific data from openstreetmap and don’t want to download the whole state or country? The solution is Overpass API.

The Overpass API (formerly known as OSM Server Side Scripting, or OSM3S) is a read-only API that serves up custom selected parts of the OSM map data. It acts as a database over the web: the client sends a query to the API and gets back the data set that corresponds to the query.

http://wiki.openstreetmap.org/wiki/Overpass_API

We are going to try the Overpass QL as query language. The whole query source code is divided in statements. We set the type of element that we want: node, way, relation or area. and then filter by tag. Like this

node[name="Foo"];
way[name="Foo"];
rel[name="Foo"];
area[name="Foo"];

If we want polygons we can use the way element. For example, let’s get all stadiums in  Pittsburgh (notice that could be more than one city called Pittsburgh in the OSM database):

http://overpass-api.de/api/interpreter?data=way["addr:city"="Pittsburgh"]["leisure"="stadium"];out geom;

You can check the result of this query here: http://overpass-turbo.eu/s/dv6

The Overpass turbo web is a great way of testing different queries, and even download the selection in geojson. You should also take a look at  the API documentation to learn how to do more complicated queries.

In case we need elements that could have two different tags we can use this syntax:

# select either stadium or sports_centre
["leisure"~"stadium|sports_centre"]

To make a query with distance we can try this statement:

# return all stadiums within 5000 m from the Boston node

node
[place] ["name"="Boston"]->.a;
(
way(around.a:5000)["leisure"="stadium"];
);
out geom;

If you need to make several queries in a row will be easier using a script. We can download the selection using wget, saving it as a xml file and then transform it to geojson(*), this could be the script to to it:

# create a file in osm format called Pittsburgh.xml:
wget "http://overpass-api.de/api/interpreter?data=way["addr:city"="Pittsburgh"]["leisure"="stadium"];out geom;" -O Pittsburgh.xml

# use osmtogeojson to transform osm data into geojson:
osmtogeojson Pittsburgh.xml > Pittsburgh.geojson

# remove the xml file
rm Pittsburgh.xml

* You need to have installed this node module: https://www.npmjs.com/package/osmtogeojson