谷歌地图在Django项目中显示多个位置

谷歌地图在Django项目中显示多个位置,django,google-maps-api-3,google-geocoder,Django,Google Maps Api 3,Google Geocoder,我想在django项目中使用GoogleMap显示多个邮件地址。地址是数据库中的变量 到目前为止,我已经尝试了django easy maps,它非常适合只显示一个地址。就像上面说的,如果你只有一个地址(可能会显示多个地址),那么它很容易使用 我还尝试了django-gmapi,它可以显示多个地址(latlng格式)。但我很难将我的美国邮政地址转换成latlng格式 因此,我的问题是: django easy maps是否支持多个地址 如何将geocoding与django-gmapi 有没有建

我想在django项目中使用GoogleMap显示多个邮件地址。地址是数据库中的变量

到目前为止,我已经尝试了
django easy maps
,它非常适合只显示一个地址。就像上面说的,如果你只有一个地址(可能会显示多个地址),那么它很容易使用

我还尝试了
django-gmapi
,它可以显示多个地址(latlng格式)。但我很难将我的美国邮政地址转换成latlng格式

因此,我的问题是:

  • django easy maps
    是否支持多个地址
  • 如何将
    geocoding
    django-gmapi
  • 有没有建议如何在Django的谷歌地图上显示多个美国邮政地址
    我也许可以帮助解决第二点…如何地理编码您现有的地址

    更新
    看起来gmapi内置了自己的地理编码助手,所以您可能不需要我在下面粘贴的任何代码。见:


    我使用了以下代码:

    import urllib
    
    from django.conf import settings
    from django.utils.encoding import smart_str
    from django.db.models.signals import pre_save
    from django.utils import simplejson as json
    
    
    def get_lat_long(location):
        output = "csv"
        location = urllib.quote_plus(smart_str(location))
        request = "http://maps.google.co.uk/maps/api/geocode/json?address=%s&sensor=false" % location
        response = urllib.urlopen(request).read()
        data = json.loads(response)
        if data['status'] == 'OK':
            # take first result
            return (str(data['results'][0]['geometry']['location']['lat']), str(data['results'][0]['geometry']['location']['lng']))
        else:
            return (None, None)
    
    def get_geocode(sender, instance, **kwargs):
        tlat, tlon = instance._geocode__target_fields
        if not getattr(instance, tlat) or not getattr(instance, tlon):
            map_query = getattr(instance, instance._geocode__src_field, '')
            if callable(map_query):
                map_query = map_query()
            lat, lon = get_lat_long(map_query)
            setattr(instance, tlat, lat)
            setattr(instance, tlon, lon)
    
    def geocode(model, src_field, target_fields=('lat','lon')):
        # pass src and target field names as strings
        setattr(model, '_geocode__src_field', src_field)
        setattr(model, '_geocode__target_fields', target_fields)
        pre_save.connect(get_geocode, sender=model)
    
    (可能是我从某个Github项目借用的,如果是,我已经失去了属性,对不起!)

    然后,在您的模型上,您需要以下内容:

    from django.db import models
    from gmaps import geocode # import the function from above
    
    class MyModel(models.Model):
        address = models.TextField(blank=True)
        city = models.CharField(max_length=32, blank=True)
        postcode = models.CharField(max_length=32, blank=True)
    
        lat = models.DecimalField(max_digits=12, decimal_places=6, verbose_name='latitude', blank=True, null=True, help_text="Will be filled automatically.")
        lon = models.DecimalField(max_digits=12, decimal_places=6, verbose_name='longitude', blank=True, null=True, help_text="Will be filled automatically.")
    
        def map_query(self):
            """
            Called on save by the geocode decorator which automatically fills the
            lat,lng values. This method returns a string to use as query to gmaps.
            """
            map_query = ''
            if self.address and self.city:
                map_query = '%s, %s' % (self.address, self.city)
            if self.postcode:
                if map_query:
                    map_query = '%s, ' % map_query
                map_query = '%s%s' % (map_query, self.postcode)
            return map_query
    
    geocode(Venue, 'map_query')
    
    然后,要对现有数据进行地理编码,您只需重新保存所有现有记录,例如:

    from .models import MyModel
    
    for obj in MyModel.objects.all():
        obj.save()
    

    我也许可以帮助解决第二点…如何地理编码您现有的地址

    更新
    看起来gmapi内置了自己的地理编码助手,所以您可能不需要我在下面粘贴的任何代码。见:


    我使用了以下代码:

    import urllib
    
    from django.conf import settings
    from django.utils.encoding import smart_str
    from django.db.models.signals import pre_save
    from django.utils import simplejson as json
    
    
    def get_lat_long(location):
        output = "csv"
        location = urllib.quote_plus(smart_str(location))
        request = "http://maps.google.co.uk/maps/api/geocode/json?address=%s&sensor=false" % location
        response = urllib.urlopen(request).read()
        data = json.loads(response)
        if data['status'] == 'OK':
            # take first result
            return (str(data['results'][0]['geometry']['location']['lat']), str(data['results'][0]['geometry']['location']['lng']))
        else:
            return (None, None)
    
    def get_geocode(sender, instance, **kwargs):
        tlat, tlon = instance._geocode__target_fields
        if not getattr(instance, tlat) or not getattr(instance, tlon):
            map_query = getattr(instance, instance._geocode__src_field, '')
            if callable(map_query):
                map_query = map_query()
            lat, lon = get_lat_long(map_query)
            setattr(instance, tlat, lat)
            setattr(instance, tlon, lon)
    
    def geocode(model, src_field, target_fields=('lat','lon')):
        # pass src and target field names as strings
        setattr(model, '_geocode__src_field', src_field)
        setattr(model, '_geocode__target_fields', target_fields)
        pre_save.connect(get_geocode, sender=model)
    
    (可能是我从某个Github项目借用的,如果是,我已经失去了属性,对不起!)

    然后,在您的模型上,您需要以下内容:

    from django.db import models
    from gmaps import geocode # import the function from above
    
    class MyModel(models.Model):
        address = models.TextField(blank=True)
        city = models.CharField(max_length=32, blank=True)
        postcode = models.CharField(max_length=32, blank=True)
    
        lat = models.DecimalField(max_digits=12, decimal_places=6, verbose_name='latitude', blank=True, null=True, help_text="Will be filled automatically.")
        lon = models.DecimalField(max_digits=12, decimal_places=6, verbose_name='longitude', blank=True, null=True, help_text="Will be filled automatically.")
    
        def map_query(self):
            """
            Called on save by the geocode decorator which automatically fills the
            lat,lng values. This method returns a string to use as query to gmaps.
            """
            map_query = ''
            if self.address and self.city:
                map_query = '%s, %s' % (self.address, self.city)
            if self.postcode:
                if map_query:
                    map_query = '%s, ' % map_query
                map_query = '%s%s' % (map_query, self.postcode)
            return map_query
    
    geocode(Venue, 'map_query')
    
    然后,要对现有数据进行地理编码,您只需重新保存所有现有记录,例如:

    from .models import MyModel
    
    for obj in MyModel.objects.all():
        obj.save()
    

    @用户1046012哦,我知道另一个问题也是你的,所以我想你已经有答案了@用户1046012哦,我知道另一个问题也是你的,所以我想你已经有答案了!