openstreetmap.py 2.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. """
  2. OpenStreetMap (Map)
  3. @website https://openstreetmap.org/
  4. @provide-api yes (http://wiki.openstreetmap.org/wiki/Nominatim)
  5. @using-api yes
  6. @results JSON
  7. @stable yes
  8. @parse url, title
  9. """
  10. from json import loads
  11. # engine dependent config
  12. categories = ['map']
  13. paging = False
  14. # search-url
  15. base_url = 'https://nominatim.openstreetmap.org/'
  16. search_string = 'search/{query}?format=json&polygon_geojson=1&addressdetails=1'
  17. result_base_url = 'https://openstreetmap.org/{osm_type}/{osm_id}'
  18. # do search-request
  19. def request(query, params):
  20. params['url'] = base_url + search_string.format(query=query)
  21. return params
  22. # get response from search-request
  23. def response(resp):
  24. results = []
  25. json = loads(resp.text)
  26. # parse results
  27. for r in json:
  28. if 'display_name' not in r:
  29. continue
  30. title = r['display_name'] or u''
  31. osm_type = r.get('osm_type', r.get('type'))
  32. url = result_base_url.format(osm_type=osm_type,
  33. osm_id=r['osm_id'])
  34. osm = {'type': osm_type,
  35. 'id': r['osm_id']}
  36. geojson = r.get('geojson')
  37. # if no geojson is found and osm_type is a node, add geojson Point
  38. if not geojson and osm_type == 'node':
  39. geojson = {u'type': u'Point', u'coordinates': [r['lon'], r['lat']]}
  40. address_raw = r.get('address')
  41. address = {}
  42. # get name
  43. if r['class'] == 'amenity' or\
  44. r['class'] == 'shop' or\
  45. r['class'] == 'tourism' or\
  46. r['class'] == 'leisure':
  47. if address_raw.get('address29'):
  48. address = {'name': address_raw.get('address29')}
  49. else:
  50. address = {'name': address_raw.get(r['type'])}
  51. # add rest of adressdata, if something is already found
  52. if address.get('name'):
  53. address.update({'house_number': address_raw.get('house_number'),
  54. 'road': address_raw.get('road'),
  55. 'locality': address_raw.get('city',
  56. address_raw.get('town', # noqa
  57. address_raw.get('village'))), # noqa
  58. 'postcode': address_raw.get('postcode'),
  59. 'country': address_raw.get('country'),
  60. 'country_code': address_raw.get('country_code')})
  61. else:
  62. address = None
  63. # append result
  64. results.append({'template': 'map.html',
  65. 'title': title,
  66. 'content': '',
  67. 'longitude': r['lon'],
  68. 'latitude': r['lat'],
  69. 'boundingbox': r['boundingbox'],
  70. 'geojson': geojson,
  71. 'address': address,
  72. 'osm': osm,
  73. 'url': url})
  74. # return results
  75. return results