Django(Geo)地理编码 - 模型上的地理编码保存不起作用

时间:2015-04-23 07:26:57

标签: django google-maps google-geocoder geodjango google-api-v3

我的模型上有这个保存覆盖:

    def save(self, **kwargs):
    if not self.location:
        address = u'%s %s %s %s' % (self.address_first, self.address_second, self.address_third, self.postcode)
        geocoder = Nominatim()
        try:
            _, latlon = geocoder.geocode(address)
        except (GeopyError, ValueError):
            pass
        else:
            latlon = geocoder.geocode(address)
            point = 'POINT({0} {1})'.format(latlon[1][1], latlon[1][0])
            self.location = geos.fromstr(point)
    super(Venue, self).save()

我正在

TypeError: 'NoneType' object is not iterable

特别是关于地址变量。它工作正常如果我硬编码地址。

我认为这与self.address ...在模型保存之后才可用的事实有关?最好的方法是什么?保存两次?

由于

在其他人遇到问题时更新。谷歌期待api请求以这样的格式获得地址Line1 + Line2 + Line3 + Zipcode,而不是Line1,line2,line,zipcode等等。所以只需在尝试和地理编码之前格式化字符串。它并不是Django / Python特有的。

def save(self, **kwargs):
    if not self.location:
        address = u'{0}, {1}, {2}'.format(self.address_second, self.address_third, self.postcode)
        address = address.replace(" ", "+").replace(',', '')
        geocoder = GoogleV3()
        try:
            _, latlon = geocoder.geocode(address)
        except (GeopyError, ValueError):
            pass
        else:
            latlon = geocoder.geocode(address)
            point = 'POINT({0} {1})'.format(latlon[1][1], latlon[1][0])
            self.location = geos.fromstr(point)
    super(Venue, self).save()

0 个答案:

没有答案