1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2013_Today OpenERP SA (<http://www.openerp.com>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
23 import simplejson as json
28 from openerp.osv import osv, fields
29 from openerp import tools
30 from openerp.tools.translate import _
34 url = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address='
35 url += urllib.quote(addr.encode('utf8'))
38 result = json.load(urllib.urlopen(url))
40 raise osv.except_osv(_('Network error'),
41 _('Cannot contact geolocation servers. Please make sure that your internet connection is up and running (%s).') % e)
42 if result['status'] != 'OK':
46 geo = result['results'][0]['geometry']['location']
47 return float(geo['lat']), float(geo['lng'])
48 except (KeyError, ValueError):
52 def geo_query_address(street=None, zip=None, city=None, state=None, country=None):
53 if country and ',' in country and (country.endswith(' of') or country.endswith(' of the')):
54 # put country qualifier in front, otherwise GMap gives wrong results,
55 # e.g. 'Congo, Democratic Republic of the' => 'Democratic Republic of the Congo'
56 country = '{1} {0}'.format(*country.split(',', 1))
57 return tools.ustr(', '.join(filter(None, [street,
58 ("%s %s" % (zip or '', city or '')).strip(),
63 class res_partner(osv.osv):
64 _inherit = "res.partner"
67 'partner_latitude': fields.float('Geo Latitude'),
68 'partner_longitude': fields.float('Geo Longitude'),
69 'date_localization': fields.date('Geo Localization Date'),
72 def geo_localize(self, cr, uid, ids, context=None):
73 # Don't pass context to browse()! We need country names in english below
74 for partner in self.browse(cr, uid, ids):
77 result = geo_find(geo_query_address(street=partner.street,
80 state=partner.state_id.name,
81 country=partner.country_id.name))
83 self.write(cr, uid, [partner.id], {
84 'partner_latitude': result[0],
85 'partner_longitude': result[1],
86 'date_localization': fields.date.context_today(self, cr, uid, context=context)