openstreetmap.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. 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/'
  17. search_string = 'search/{query}?format=json&polygon_geojson=1&addressdetails=1'
  18. result_base_url = 'https://openstreetmap.org/{osm_type}/{osm_id}'
  19. # do search-request
  20. def request(query, params):
  21. params['url'] = base_url + search_string.format(query=query)
  22. # using searx User-Agent
  23. params['headers']['User-Agent'] = searx_useragent()
  24. return params
  25. # get response from search-request
  26. def response(resp):
  27. results = []
  28. json = loads(resp.text)
  29. # parse results
  30. for r in json:
  31. if 'display_name' not in r:
  32. continue
  33. title = r['display_name']
  34. osm_type = r.get('osm_type', r.get('type'))
  35. url = result_base_url.format(osm_type=osm_type,
  36. osm_id=r['osm_id'])
  37. osm = {'type': osm_type,
  38. 'id': r['osm_id']}
  39. geojson = r.get('geojson')
  40. # if no geojson is found and osm_type is a node, add geojson Point
  41. if not geojson and osm_type == 'node':
  42. geojson = {u'type': u'Point', u'coordinates': [r['lon'], r['lat']]}
  43. address_raw = r.get('address')
  44. address = {}
  45. # get name
  46. if r['class'] == 'amenity' or\
  47. r['class'] == 'shop' or\
  48. r['class'] == 'tourism' or\
  49. r['class'] == 'leisure':
  50. if address_raw.get('address29'):
  51. address = {'name': address_raw.get('address29')}
  52. else:
  53. address = {'name': address_raw.get(r['type'])}
  54. # add rest of adressdata, if something is already found
  55. if address.get('name'):
  56. address.update({'house_number': address_raw.get('house_number'),
  57. 'road': address_raw.get('road'),
  58. 'locality': address_raw.get('city',
  59. address_raw.get('town', # noqa
  60. address_raw.get('village'))), # noqa
  61. 'postcode': address_raw.get('postcode'),
  62. 'country': address_raw.get('country'),
  63. 'country_code': address_raw.get('country_code')})
  64. else:
  65. address = None
  66. # append result
  67. results.append({'template': 'map.html',
  68. 'title': title,
  69. 'content': '',
  70. 'longitude': r['lon'],
  71. 'latitude': r['lat'],
  72. 'boundingbox': r['boundingbox'],
  73. 'geojson': geojson,
  74. 'address': address,
  75. 'osm': osm,
  76. 'url': url})
  77. # return results
  78. return results