openstreetmap.py 3.0 KB

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