sam23
sam23

Reputation: 599

How To Find Nearest Point From User Location using geodjango?

I am trying to find the nearest point to a location using 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).

I need to find the point nearest to the user without using any limit during query.

Upvotes: 15

Views: 5395

Answers (2)

John Moutafis
John Moutafis

Reputation: 23134

Let's assume that your LocationInfo has it's geometry field named position:

For Django version >= 1.9:

You can use the Distance() function:

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

For Django 1.6 <= version < 1.9:

You can use the .distance() method:

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

For Django version < 1.6:

The .first() method does not exist so you have to get the first of the ordered queryset as follows:

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

Upvotes: 21

Dawn T Cherian
Dawn T Cherian

Reputation: 5406

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

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

class LocationInfo(models.Model):

    geo_objects = gis_models.GeoManager()

Upvotes: 0

Related Questions