简体   繁体   English

如何使用geodjango从用户位置找到最近点?

[英]How To Find Nearest Point From User Location using geodjango?

I am trying to find the nearest point to a location using geodjango. 我试图使用geodjango找到距离某个位置最近的点。

I tried using the following code: 我尝试使用以下代码:

LocationInfo.objects.filter(coordinates__distance_lte=(user_location, D(km=2)))

But It only works if the location is within the specified distance ( D(km=2) in this case). 但它仅在位置在指定距离内时才有效D(km=2)在这种情况下为D(km=2) )。

I need to find the point nearest to the user without using any limit during query. 我需要在查询过程中找到离用户最近的点而不使用任何限制。

Let's assume that your LocationInfo has it's geometry field named position : 假设您的LocationInfo具有名为position的几何字段:

For Django version >= 1.9: 对于Django版本> = 1.9:

You can use the Distance() function: 您可以使用Distance()函数:

from django.contrib.gis.db.models.functions import Distance

LocationInfo.objects.annotate(
    distance=Distance('position', user_location)
).order_by('distance').first()

Which will return the nearest object to the user_location 这将返回最近的user_location对象

For Django 1.6 <= version < 1.9: 对于Django 1.6 <=版本<1.9:

You can use the .distance() method: 您可以使用.distance()方法:

LocationInfo.objects.distance(user_location).order_by('distance').first()

For Django version < 1.6: 对于Django版本<1.6:

The .first() method does not exist so you have to get the first of the ordered queryset as follows: .first()方法不存在,因此您必须获取有序查询集的第一个,如下所示:

 LocationInfo.objects.distance(user_location).order_by('distance')[:1].get()

This will give you the nearest location info: 这将为您提供最近的位置信息:

LocationInfo.geo_objects.distance(user_location).order_by('distance')[0]

where geo_objects is Model manager for LocationInfo 其中geo_objects是LocationInfo的模型管理器

from django.contrib.gis.db import models as gis_models

class LocationInfo(models.Model):

    geo_objects = gis_models.GeoManager()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM