Google 地图显示 Django 项目中的多个位置

发布于 2024-12-15 18:08:57 字数 409 浏览 2 评论 0原文

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

到目前为止,我已经尝试过 django-easy-maps ,它非常适合仅显示一个地址。就像它所说的那样,如果您只有一个地址(也许能够显示多个地址),那么它非常容易使用。

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

所以我的问题是:

  1. django-easy-maps 是否支持多个地址?
  2. 如何使用 geocodingdjango-gmapi
  3. 有什么建议如何在 Django 的 Google 地图上显示多个美国邮政地址吗?

I want to use Google map to show more than one mail address in my django project. The addresses are variables from the database.

Till now, I have tried django-easy-maps which is great for showing only ONE address. Like it said it is very easy to use if you have only one address (may be able to show more than one).

I also tried django-gmapi which can show more than one address (in latlng format). But I have a hard time to convert my us post address to latlng format.

So my questions are:

  1. Does django-easy-maps support more than one address?
  2. How to use geocoding with django-gmapi
  3. Any suggestions how to show more than one us post address on Google map in Django?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

铁轨上的流浪者 2024-12-22 18:08:57

我也许可以帮助解决第 2 点……如何对现有地址进行地理编码。

更新
看起来 gmapi 内置了自己的地理编码助手,因此您可能不需要我在下面粘贴的任何代码。请参阅:有人有使用 django-gmapi 进行地理编码的经验吗?< /a>


我使用了以下代码:(

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()

I can maybe help address point 2 ...how to geocode your existing addresses.

UPDATE
It looks like gmapi has it's own geocoding helper built in so you probably don't need any of the code I pasted below. See: Does anybody has experiences with geocoding using django-gmapi?


I have used the following code:

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)

(Possibly I borrowed it from a Github project somewhere, I have lost the attribution if so, sorry!)

Then on your model you need something like:

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')

Then to geocode your existing data you could just re-save all the existing records, eg:

from .models import MyModel

for obj in MyModel.objects.all():
    obj.save()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文