[英]Geo Django get cities from latitude and longitude
I'm learning how to use Geo Django. 我正在学习如何使用Geo Django。 When a user registers I save the latitude and longitude information as seen below:
当用户注册时,我保存纬度和经度信息,如下所示:
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
class GeoModel(models.Model):
"""
Abstract model to provide GEO fields.
"""
latitude = models.FloatField(blank=True, null=True, verbose_name='Latitude')
longitude = models.FloatField(blank=True, null=True, verbose_name='Longitude')
location = models.PointField(blank=True, null=True)
class Meta:
abstract = True
def save(self, *args, **kwargs):
if self.latitude and self.longitude:
self.location = Point(float(self.latitude), float(self.longitude))
super(GeoModel, self).save(*args, **kwargs)
Next I want to add a new field called city
where **I want to store the city "name" ie London based the long and lat details given. 接下来我想添加一个名为
city
的新字段,其中**我想存储城市“名称”,即伦敦基于给出的long和lat详细信息。
I have looked at django-cities
where is saves a database of cities from Geo Name, but this seems overkill and not Python 3 compatible so a no go for me. 我已经看过
django-cities
,它们从Geo Name中保存了一个城市数据库,但是这看起来有些过分而且不兼容Python 3,所以对我来说不行。 I have seen a package called geopy but this seems to completely replace Geo Django and uses Google API which comes with restrictions. 我见过一个名为geopy的软件包,但这似乎完全取代了Geo Django并使用了带有限制的Google API。
I want to stick with Geo Django and somehow do a lookup to find out the City name based on long and lat so what are my options? 我想坚持使用Geo Django并以某种方式进行查找以找出基于long和lat的城市名称,那么我的选择是什么? ie.
即。
Is above the correct way to approach this? 接近这个是正确的方法吗? If so how do I get the data into my DB then do a lookup on it using Geo Django to find the city name?
如果是这样,我如何将数据存入我的数据库,然后使用Geo Django查找城市名称?
You have several solutions to do this: 你有几个解决方案来做到这一点:
Create another model City 创建另一个模型城市
from django.contrib.gis.db import models class City(models.Model): name = models.CharField(max_lenght=255) geometry = models.MultiPolygonField() objects = models.GeoManager()
Then you can find the name of the city containing your location with: 然后,您可以找到包含您所在位置的城市名称:
geomodel = GeoModel(...)
city = City.objects.get(geometry__contains=geomodel.location)
city_name = city.name
Depending on the country/region you are interested in, you may find city geometries to fill the City table in OpenData (eg http://www.gadm.org/country (not tested but seems to propose open shapefiles)) 根据您感兴趣的国家/地区,您可以找到城市几何图形以填充OpenData中的City表格(例如http://www.gadm.org/country (未经测试但似乎建议打开shapefile))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.