我将坐标存储为数据库中的纬度经度对。现在,我需要从给定的lat-long坐标中检索给定半径内的所有条目。例如,如果给定坐标48.796777,2.371140和距离20公里,它将从该点起20公里内检索所有记录。
如果它提供任何简化或导致更少的CPU时间,它的准确性足以计算"直接"点之间的距离,即不需要考虑地球的曲率。
如何通过Django实现这一目标?更具体地说,如何为这样的查询构建视图(可能还有模型)?
答案 0 :(得分:8)
您应该使用GeoDjango。它允许您对地理数据库条目执行distance queries。
from django.contrib.gis.measure import D
from django.contrib.gis.geos import *
from myapp.models import MyResult
pnt = fromstr('POINT(48.796777 2.371140 )', srid=4326)
qs = MyResult.objects.filter(point__distance_lte=(pnt, D(km=20)))
答案 1 :(得分:2)
您可以使用geopy
from geopy import distance
_, ne = g.geocode('Newport, RI')
_, cl = g.geocode('Cleveland, OH')
distance.distance(ne, cl).miles
# 538.37173614757057
若要优化,您可以过滤用户对象,以便首先粗略估算附近用户。这样您就不必遍历db中的所有用户。这种粗略估计是可选的。为了满足您的所有项目要求,您可能需要编写一些额外的逻辑:
#The location of your user.
lat, lng = 41.512107999999998, -81.607044999999999
min_lat = lat - 1 # You have to calculate this offsets based on the user location.
max_lat = lat + 1 # Because the distance of one degree varies over the planet.
min_lng = lng - 1
max_lng = lng + 1
users = User.objects.filter(lat__gt=min_lat, lat__lt=max__lat, lat__gt=min_lat, lat__lt=max__lat)
# If not 20 fall back to all users.
if users.count() <= 20:
users = User.objects.all()
答案 2 :(得分:0)
试试这段代码。 我正在使用python,sqlalchemy
此sqlalchemy查询返回给定point.its工作正确的最近对象。但此查询返回所有模型。但它的工作正常。
我的模特课
#<jaxb:bindings
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
jaxb:version="2.1">
<jaxb:bindings schemaLocation="--schemalocation here--">
<jaxb:bindings node="//xs:schema[@targetNamespace='--namespace here--']">
<jaxb:schemaBindings>
<jaxb:package name="--packagename here--" />
</jaxb:schemaBindings>
</jaxb:bindings>
</jaxb:bindings>
我的查询
#class City(Base):
__tablename__ = "tbl_City"
city_id = Column(Integer, primary_key=True, unique=True)
geo_coordinates = Column(Geometry('POINT', srid=4326))
答案 3 :(得分:-1)
我认为最好的方法是像Timmy建议的那样使用GeoDjango,但是你必须拥有一个支持Geo的后端(如PosGis)。但是,如果您的模型包含自定义纬度和经度字段,我认为不可能使用
class CustomGeoModel(models.Model):
lat = models.CharField(max_length=30)
lon = models.CharField(max_length=30)