Skip to content

Commit

Permalink
merging @mharnold s changes
Browse files Browse the repository at this point in the history
  • Loading branch information
mvexel committed Nov 24, 2014
2 parents 4f6e46a + 20c1582 commit e74316f
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 25 deletions.
10 changes: 7 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
*~
*.swp
.DS_Store
*.pyc
build
dist
overpass.egg-info

/build/
/dist/
/*.egg-info
50 changes: 32 additions & 18 deletions overpass/api.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import sys
import requests
import json
from shapely.geometry import Point

import geojson

class API(object):
"""A simple Python wrapper for the OpenStreetMap Overpass API"""
Expand All @@ -15,6 +14,7 @@ class API(object):
_bbox = [-180.0, -90.0, 180.0, 90.0]

_QUERY_TEMPLATE = "[out:{responseformat}];{query}out body;"
_GEOJSON_QUERY_TEMPLATE = "[out:json];{query}out body geom;"

def __init__(self, *args, **kwargs):
self.endpoint = kwargs.get("endpoint", self._endpoint)
Expand Down Expand Up @@ -42,7 +42,7 @@ def Get(self, query, asGeoJSON=False):

try:
response = json.loads(self._GetFromOverpass(
self._ConstructQLQuery(query)))
self._ConstructQLQuery(query, asGeoJSON=asGeoJSON)))
except OverpassException as oe:
print(oe)
sys.exit(1)
Expand All @@ -60,12 +60,18 @@ def Search(self, feature_type, regex=False):
"""Search for something."""
pass

def _ConstructQLQuery(self, userquery):
def _ConstructQLQuery(self, userquery, asGeoJSON=False):
raw_query = str(userquery)
if not raw_query.endswith(";"):
raw_query += ";"

complete_query = self._QUERY_TEMPLATE.format(responseformat=self.responseformat, query=raw_query)
if asGeoJSON:
template = self._GEOJSON_QUERY_TEMPLATE
else:
template = self._QUERY_TEMPLATE

complete_query = template.format(responseformat=self.responseformat, query=raw_query)

if self.debug:
print(complete_query)
return complete_query
Expand Down Expand Up @@ -96,20 +102,28 @@ def _GetFromOverpass(self, query):
return r.text

def _asGeoJSON(self, elements):
"""construct geoJSON from elements"""
nodes = [{
"id": elem.get("id"),
"tags": elem.get("tags"),
"geom": Point(elem["lon"], elem["lat"])}
for elem in elements if elem["type"] == "node"]
ways = [{
"id": elem.get("id"),
"tags": elem.get("tags"),
"nodes": elem.get("nodes")}
for elem in elements if elem["type"] == "way"]
print(nodes)
print(ways)
#print 'DEB _asGeoJson elements:', elements

features = []
for elem in elements:
elem_type = elem["type"]
if elem["type"] == "node":
geometry=geojson.Point((elem["lon"], elem["lat"]))
elif elem["type"] == "way":
points = []
for coords in elem["geometry"]:
points.append((coords["lon"], coords["lat"]))
geometry = geojson.LineString(points)
else:
continue

feature = geojson.Feature(
id=elem["id"],
geometry=geometry,
properties=elem.get("tags"))
features.append(feature)

return geojson.FeatureCollection(features)

class OverpassException(Exception):
def __init__(self, status_code, message):
Expand Down
1 change: 0 additions & 1 deletion requirements.txt

This file was deleted.

2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@
download_url='https://github.com/mvexel/overpass-api-python-wrapper/tarball/0.0.1',
keywords=['openstreetmap', 'overpass', 'wrapper'],
classifiers=[],
install_requires=['requests>=2.3.0', 'shapely>=1.4.3'],
install_requires=['requests>=2.3.0', 'geojson>=1.0.9'],
)
22 changes: 20 additions & 2 deletions test_api.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,27 @@
import geojson
import overpass


class TestAPI:

def test_initialize_api(self):
api = overpass.API()
assert isinstance(api, overpass.API)
assert api.debug == False
assert api.debug == False

def test_geojson(self):
api = overpass.API()
#osm_elements = api.Get(overpass.MapQuery(37.86517,-122.31851,37.86687,-122.31635))
#print 'DEB osm_elements:', geojson.dumps(osm_elements,sort_keys=True,indent=2)
osm_geo = api.Get(overpass.MapQuery(37.86517,-122.31851,37.86687,-122.31635), asGeoJSON=True)
#with open('test.geojson','w') as f:
# geojson.dump(osm_geo,f,indent=2,sort_keys=True)
assert len(osm_geo['features'])>1

def run_tests(self):
self.test_initialize_api()
self.test_geojson()

if __name__ == '__main__':
tapi = TestAPI()
tapi.run_tests()
print "overpass PASS"

0 comments on commit e74316f

Please sign in to comment.