from django.db import models from math import acos, cos, sin class GeoCoordinate(object): def __init__(self,latitude=0.00,longitude=0.00): self.latitude = latitude self.longitude = longitude def within_radius(self,r,geocoordn_obj): print geocoordn_obj.__dict__ if acos(sin(geocoordn_obj.latitude)*sin(self.latitude) + \ cos(geocoordn_obj.latitude)*cos(self.latitude)*cos(self.longitude -(geocoordn_obj.longitude)))*6371 <=r: return True else: return False def __repr__(self): return str(self.latitude) + ',' + str(self.longitude) class GeoCoordinateField(models.Field): description = "A latitude,longitude pair" __metaclass__ = models.SubfieldBase def __init__(self,help_text=("A comma-separated latitude longitude pair"),verbose_name='geocordfield', *args,**kwargs): self.name="GeoCoordinateField", self.through = None self.help_text = help_text self.blank = True self.editable = True self.creates_table = False self.db_column = None self.serialize = False self.null = True self.creation_counter = models.Field.creation_counter models.Field.creation_counter += 1 super(GeoCoordinateField, self).__init__(*args, **kwargs) def db_type(self, connection): return 'varchar(100)' def to_python(self,value): if value in ( None,''): return GeoCoordinate() else: if isinstance(value, GeoCoordinate): return value else: args = [float(value.split(',')[0]),float(value.split(',')[1])] if len(args) != 2 and value is not None: raise ValidationError("Invalid input for a GeoCoordinate instance") return GeoCoordinate(*args) def get_internal_type(self): return 'CharField' def value_to_string(self, obj): value = self._get_val_from_obj(obj) return self.get_prep_value(value)