Skip to content

Instantly share code, notes, and snippets.



Last active Aug 29, 2015
What would you like to do?
from decimal import Decimal
from django.db import models, connection
class LocationManager(models.Manager):
def find_nearby(self, latitude, longitude, radius, is_miles=True):
Uses Spherical Law of Cosines to determine places within a radial distance
latitude = Decimal(latitude)
longitude = Decimal(longitude)
radius = int(radius)
if is_miles:
distance_unit = 3959 # Earth radius mi
distance_unit = 6371 # Earth radius km
cursor = connection.cursor()
sql = """SELECT id, latitude, longitude
FROM places_place AS distance WHERE
(%f * acos(cos(radians(%f)) * cos(radians(latitude)) *
cos(radians(longitude) - radians(%f)) +
sin(radians(%f)) * sin(radians(latitude)))) < %d
ORDER BY distance
""" % (distance_unit, latitude, longitude, latitude, radius)
ids = [row[0] for row in cursor.fetchall()]
return self.filter(pk__in=ids)
from django.db imports models
from django.conf import settings
from .managers import LocationManager
class Place(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
latitude = models.DecimalField(max_digits=9, decimal_places=6)
longitude = models.DecimalField(max_digits=9, decimal_places=6)
objects = LocationManager()
def __unicode__(self):
return u'%s, %s' % (self.latitude, self.longitude)
{% for user in user_list %}
<li>{{ user.username }}</li>
{% endfor %}
from django.shortcuts import render_to_response
from .models import Place
def index(request):
# Chicago
latitude = 41.87811
longitude = -87.62980
radius = 10
places = Place.objects.find_nearby(latitude, longitude, radius)
user_list = User.objects.filter(place__in=places).distinct('user')
return render_to_response('template.html', {'user_list': user_list})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment