Skip to content

Instantly share code, notes, and snippets.

@Gonzillaaa
Forked from renyi/managers.py
Created May 19, 2014 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gonzillaaa/5a0a6832709438797687 to your computer and use it in GitHub Desktop.
Save Gonzillaaa/5a0a6832709438797687 to your computer and use it in GitHub Desktop.
from geopy import units, distance
from mezzanine.core.managers import CurrentSiteManager
class GeoManager(CurrentSiteManager):
def near(self, latitude=None, longitude=None, distance_range=30):
queryset = super(GeoManager, self).get_query_set()
if not (latitude and longitude and distance_range):
return queryset.none()
latitude = float(latitude)
longitude = float(longitude)
distance_range = float(distance_range)
rough_distance = units.degrees(arcminutes=units.nautical(kilometers=distance_range)) * 2
queryset = queryset.filter(
latitude__range=(
latitude - rough_distance,
latitude + rough_distance
),
longitude__range=(
longitude - rough_distance,
longitude + rough_distance
)
)
locations = []
for location in queryset:
if location.latitude and location.longitude:
exact_distance = distance.distance(
(latitude, longitude),
(location.latitude, location.longitude)
).kilometers
if exact_distance <= distance_range:
locations.append(location)
queryset = queryset.filter(id__in=[l.id for l in locations])
return queryset
from geopy import geocoders
from geopy.geocoders.google import GQueryError
class BaseGeo(models.Model):
location = models.TextField(_('Address'), blank=True)
latitude = models.FloatField(_('Latitude'), blank=True, null=True)
longitude = models.FloatField(_('Longitude'), blank=True, null=True)
place = models.TextField(_('Place'), blank=True)
objects = GeoManager()
class Meta:
abstract = True
def save(self, domain='maps.google.com.my', *args, **kwargs):
location = self.location
if location:
if not self.latitude or not self.longitude:
try:
g = geocoders.Google(domain=domain)
self.place, (self.latitude, self.longitude) = g.geocode(location)
except GQueryError:
pass
except Exception, e:
print '%s' % e
super(BaseGeo, self).save(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment