You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.6 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2004-2015 Odoo S.A. (original module : base_geolocalize)
  3. # © 2018 Le Filament (<http://www.le-filament.com>)
  4. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
  5. import json
  6. import urllib2
  7. from odoo import api, fields, models, tools, _
  8. from odoo.exceptions import UserError
  9. def geo_find(addr):
  10. if not addr:
  11. return None
  12. url = 'https://nominatim.openstreetmap.org/search.php/'
  13. url += urllib2.quote(addr.encode('utf8'))
  14. url += '?format=json'
  15. try:
  16. result = json.load(urllib2.urlopen(url))
  17. except Exception as e:
  18. raise UserError(_('Cannot contact geolocation servers. Please make '
  19. 'sure that your Internet connection is up and '
  20. 'running (%s).') % e)
  21. try:
  22. if result:
  23. geo = result[0]
  24. return [float(geo['lat']), float(geo['lon'])]
  25. else:
  26. return None
  27. except (KeyError, ValueError):
  28. return None
  29. def geo_query_address(street=None, zip=None,
  30. city=None, state=None, country=None):
  31. if (country and ',' in country
  32. and (country.endswith(' of') or country.endswith(' of the'))):
  33. country = '{1} {0}'.format(*country.split(',', 1))
  34. return tools.ustr(', '.join(filter(None, [street, ("%s %s" % (
  35. zip or '', city or '')).strip(), state, country])))
  36. class ResPartner(models.Model):
  37. _inherit = "res.partner"
  38. partner_latitude = fields.Float(string='Geo Latitude', digits=(16, 5))
  39. partner_longitude = fields.Float(string='Geo Longitude', digits=(16, 5))
  40. date_localization = fields.Date(string='Geolocation Date')
  41. @api.multi
  42. def geo_localize(self):
  43. # We need country names in English below
  44. for partner in self.with_context(lang='en_US'):
  45. if partner.city:
  46. result = geo_find(geo_query_address(
  47. street=partner.street,
  48. zip=partner.zip, city=partner.city,
  49. country=partner.country_id.name
  50. ))
  51. if result is None:
  52. result = geo_find(geo_query_address(
  53. city=partner.city,
  54. country=partner.country_id.name
  55. ))
  56. if result:
  57. partner.write({
  58. 'partner_latitude': result[0],
  59. 'partner_longitude': result[1],
  60. 'date_localization': fields.Date.context_today(partner)
  61. })
  62. return True