-
-
Save Gonzillaaa/5a0a6832709438797687 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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