8

I am looking for a solution that works with the overpass api.

for example:

http://overpass-api.de/api/interpreter?data=[out:geojson];area(3600225494);(node(area)[%22amenity%22~%22theatre|cinema|arts_centre%22];);out%20body;

When trying this approach I get an error that says

"Error: line 1: static error: For the attribute "output" of the element "osm-script" the only allowed values are "xml", "json", "csv", "custom", or "popup"."

Therefore GeoJSON is not supported this way.

I tried several approaches in ipython (python 2.7) to transform json into geojson, but failed so far.

What I need is a way to get OSM as geojson in ipython via using a url (e.g. overpass api).

BR

0

6 Answers 6

10

Overpass API doesn't support GeoJSON. You have to perform the conversion from JSON to GeoJSON yourself.

For converting JSON into GeoJSON see this answer. It even contains a solution in Python. Another Python solution is contained in this answer.

4
  • Thanks! For confirming/clarifying my issue and also providing a possible solution. Will try it out the first solution and let you know later. The second solution I already tried and hat some problem with the d["lon"]
    – Apachai
    Dec 7, 2016 at 13:56
  • 3
    To elaborate: adding geojson output to the overpass API was discussed and rejected here github.com/drolbr/Overpass-API/issues/48, because semantics are unclear for e.g. closed ways. They then mention github.com/tyrasd/osmtogeojson as a way to produce geojson from OSM data.
    – til_b
    Dec 7, 2016 at 14:23
  • @scai I tried it out and both approaches return a KeyError: KeyError Traceback (most recent call last) <ipython-input-152-f46acadcf165> in <module>() ----> 1 v = convert_json(data) <ipython-input-151-b6174edc078d> in convert_json(items) 10 if key not in ('lat', 'lon') } 11 } ---> 12 for feature in json.loads(items) 13 ] 14 }) KeyError: 'lon'
    – Apachai
    Dec 7, 2016 at 20:57
  • 1
4

It is possible now to retrieve a GeoJSON object of OSM relation with Overpass convert function, here is an example:

[out:json];
( way(51.477,-0.001,51.478,0.001)[name="Blackheath Avenue"];
  node(w);
  relation(51.477,-0.001,51.478,0.001); );
convert item ::=::,::geom=geom(),_osm_type=type();
out geom;

Overpass Turbo query »

This example I've found here but the documentation about this feature is too scarce yet. So I've posted a feature request to improve it: https://github.com/drolbr/overpass-doc/issues/11

1

I'm getting the result as wellformed GeoJSON using the following query

import overpass

api = overpass.API()
result = api.get(
    'way["place"="neighbourhood"](37.964522,-78.573741,38.097572,-78.415126);',
    responseformat = "geojson",
    verbosity = "geom"
)
0

I developed a slightly clunky approach using Pandas and GeoPandas. Posting in case it's useful, especially to someone who might be looking for GeoJSON to use with GeoPandas in the first place. Basically, the flow is:

overpass JSON > Pandas > GeoPandas > GeoJSON

import requests
import pandas as pd
import geopandas as gp
from shapely.geometry import Point

def get_overpass_gdf(query_string):

    # Retrieve URL contents
    r = requests.get(query_string)

    # Make dataframe
    df = pd.DataFrame(r.json()['elements'])

    # Make geodataframe
    df['geometry'] = [Point(xy) for xy in zip(df.lon, df.lat)]
    df = gp.GeoDataFrame(df, geometry='geometry')

    return df

# Specify query
query_string = 'http://overpass-api.de/api/interpreter?data=[out:json];area(3600225494);(node(area)[%22amenity%22~%22theatre%7Ccinema%7Carts_centre%22];);out%20body;'

# Export to GeoJSON
gdf = get_overpass_gdf(query_string)
gdf.to_file("query_results.json", driver="GeoJSON")
1
  • 1
    Note that this code only works with nodes. It does not support ways and relations, nor out center; to process the center point of a way.
    – mmd
    Nov 2, 2019 at 10:09
0

Python package to convert OSM/Overpass XML to GeoJSON osm2geojson.

I have some problems with your example. But I made similar:

import requests
import urllib
import codecs
import json
from osm2geojson import json2geojson

OVERPASS = "https://overpass-api.de/api/interpreter/"


def overpass_call(query):
    encoded = urllib.parse.quote(query.encode('utf-8'), safe='~()*!.\'')
    r = requests.post(OVERPASS,
                      data=f"data={encoded}",
                      headers={'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'})
    if not r.status_code is 200:
        raise requests.exceptions.HTTPError('Overpass server respond with status '+str(r.status_code))
    return r.text


def save_data(data, geom_file):
    json_data = json.dumps(data, indent=2)
    f = codecs.open(geom_file, 'w')
    f.write(json_data)
    f.close()


data = overpass_call(f"""
    [out:json];
    node["amenity"~"theatre|cinema|arts_centre"](50.33, 30.30, 50.57, 30.68);
    out geom;
""")

geojson_data = json2geojson(data)
save_data(geojson_data, 'art.geojson')

0

I tried osm2geojson and it seems to work well with nodes and ways. Relations present issues. Below the code to get GeoJSON with Overpass API (providing lat, long and distance):

import osm2geojson
import requests
import json
overpass_url = "http://overpass-api.de/api/interpreter"

def lines_OSM(query, lat, lon, radious, output):
        overpass_query = """
        [out:json];
        (node"""+query+"""(around:"""+radious+""","""+lat+""","""+lon+""");
        way"""+query+"""(around:"""+radious+""","""+lat+""","""+lon+""");
        relation"""+query+"""(around:"""+radious+""","""+lat+""","""+lon+""");
        );
        out geom;
        >;
        out skel qt;
        """
        response = requests.get(overpass_url,params={'data': overpass_query})
        data = response.json()
        data = osm2geojson.json2geojson(data)
        add_dict(data)
        json.dump(data,open(output,'w' ))

Function arguments (I'll write an example)

query = """["amenity"="bicycle_parking"]"""
lat = "51.462091"
lon = "-0.192376"
radious = "5000"
output = "path_to_your_geojson/yourfile.geojson"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.