Example #1
0
 def save(self):
     if self.latitude != None and len(self.latitude) > 0 and self.longitude != None and len(self.longitude) > 0:
         lString = 'POINT(%s %s)' % (self.longitude.strip(), self.latitude.strip())
         self.map_location = fromstr(lString)
         self.point = fromstr(lString)
     self.last_modified = datetime.now()
     super(Band, self).save()
Example #2
0
 def test_apply_filters_custom(self):
     '''
         Verify that custom location filter applies to queryset when passed in.
     '''
     pnt = fromstr('POINT(%s %s)' % (-77, 39), srid=4326)
     the_dict = {'custom': Q(location__distance_lte=(pnt, D(mi=0.1)))}
     retval = self.the_resource.apply_filters(None, the_dict)
     self.assertEquals(retval.count(), 1)
Example #3
0
File: models.py Project: zouf/as2
 def save(self):
     
     #dont redo this if lat and lng is set
     if (not self.lat and not self.lon) or (self.lat == 0 and self.lon==0):
         
         loc = self.address + " " + self.city + ", " + self.state        
         location = urllib.quote_plus(smart_str(loc))
         
         dd = urllib2.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false" % location).read() 
         ft = simplejson.loads(dd)
         zipcode = None
         lat = None
         lng = None
         if ft["status"] == 'OK':
             lat = str(ft["results"][0]['geometry']['location']['lat']) 
             lng = str(ft["results"][0]['geometry']['location']['lng'])
             zipcode = None
             for jsonStr in ft["results"][0]['address_components']:
 #                print jsonStr
                 if 'types' in jsonStr:
                     for tp in jsonStr['types']:
                         if tp == "postal_code":
                             zipcode = jsonStr['long_name']
                             break
         if zipcode is not None:
             self.zipcode  = zipcode
         else:
             self.zipcode = ''
     else:
         #use existing lat lng
         lat = self.lat
         lng = self.lon
         
     if lat and lng:
         self.lat = lat
         self.lon = lng 
         self.geom = fromstr('POINT('+str(self.lon)+ ' '+str(self.lat)+')', srid=4326)
         self.point = fromstr('POINT('+str(self.lon)+ ' '+str(self.lat)+')')
     else:
         self.lat = 0
         self.lon = 0 
         self.geom = fromstr('POINT('+str(self.lon)+ ' '+str(self.lat)+')', srid=4326)
         self.point = fromstr('POINT('+str(self.lon)+ ' '+str(self.lat)+')')
     super(InterestedBusiness, self).save()
Example #4
0
    def build_filters(self, filters=None, ignore_bad_filters=False):
        if filters is None:
            filters = {}
        orm_filters = super(CigarShopResource, self).build_filters(filters)

        if 'lat' in filters and 'long' in filters and 'distance' in filters:
            pnt = fromstr('POINT(%s %s)' % (filters['long'], filters['lat']), srid=4326)
            orm_filters.update({'custom': Q(location__distance_lte=(pnt, D(mi=filters['distance'])))})

        return orm_filters
Example #5
0
def create_shop(request):
    ''' create a cigarshop no auth '''
    json_in = json.loads(request.body)
    the_user = User.objects.get(username=json_in['username'])
    cigar_shop = CigarShop(name=json_in['name'],
                           location=fromstr('POINT(%s %s)' % (float(json_in['long']),
                                                              float(json_in['lat'])), srid=4326),
                           owner=the_user)
    cigar_shop.save()
    return JsonResponse({'new_shop_id': cigar_shop.pk})
Example #6
0
File: views.py Project: zouf/as2
def get_nearby_businesses(mylat,mylng,distance=3):

    #current_pg_point = "point '({:.5f}, {:.5f})'".format(mylng, mylat)
    all_buses = Business.objects.all()
    pnt = fromstr('POINT('+str(mylng)+ ' '+str(mylat)+')', srid=4326)
    nearby_buses =  all_buses.filter(geom__distance_lte=(pnt, D(mi=DISTANCE)))
    with_distances = []
    print('before')
    for b in nearby_buses.distance(pnt):
        with_distances.append(b)
    print('after')
    return with_distances
Example #7
0
    def get(self, request):
        areas = request.GET.getlist('allegation__areas__id')
        ignore_filters = ['allegation__areas__id']
        if areas:
            self.orig_query_dict = request.GET.copy()
            schools = Area.objects.filter(pk__in=areas, type='school-grounds')
            areas = list(schools.values_list('pk', flat=True))
            if areas:
                self.orig_query_dict.setlist('allegation__areas__id', areas)
                ignore_filters = []
        officer_allegations = self.get_officer_allegations(
            ignore_filters=ignore_filters)
        allegation_pks = list(
            officer_allegations.values_list('allegation__pk', flat=True))
        ret = {'features': [], 'type': 'FeatureCollection'}

        if len(allegation_pks) > 0:
            allegation_pks = ",".join(str(x) for x in allegation_pks)
            kursor = connection.cursor()

            grid_size = 0.0005

            kursor.execute('''
                SELECT
                    COUNT( point ) AS count,
                    ST_AsText( ST_Centroid(ST_Collect( point )) ) AS center
                FROM common_allegation WHERE point IS NOT NULL and id in (%s)
                GROUP BY
                    ST_SnapToGrid( ST_SetSRID(point, 4326), %s, %s)
                ''' % (allegation_pks, grid_size, grid_size)
                )
            kclusters = kursor.fetchall()

            for cluster in kclusters:
                point = fromstr(cluster[1])
                allegation_json = {
                    "type": "Feature",
                    "properties": {

                    },
                    'geometry': {
                        'coordinates': [point.x, point.y],
                        'type': 'Point'
                    }
                }
                ret['features'].append(allegation_json)

        content = json.dumps(ret)
        return HttpResponse(content)
Example #8
0
 def get_nearest(self, request, *args, **kwargs):
     #-82.1013183593750000 40.1766586303710014
     logger.error('NearestUserViewSet: ' +kwargs['latitude']+' '+kwargs['longitude'])
     current_user = request.user
     
     pref_qs = Preferences.objects.all()
     preferences = get_object_or_404(pref_qs, user=current_user)
     # Get the current date
     now = date.today()
     
     min_date = now - relativedelta(years=preferences.max_age)
     max_date = now - relativedelta(years=preferences.min_age)
     
     logger.error('min_date ' + str(min_date))
     logger.error('max_date ' + str(max_date))
     
     distance_pref = preferences.distance
     gender_pref = preferences.gender_pref
     logger.error('Preferences: Gender ' + gender_pref + ' distance ' + str(distance_pref))
     # Filter for all prospects already processed by user
     match_set = Match.objects.filter(Q(source=current_user) | Q(target=current_user)).all()
     #for prospect in match_set:
     email_set = set()
     for x in match_set:
         logger.error('Matched emails ' + x.source.email +' and ' + x.target.email)
         email_set.add(x.source.email)
         email_set.add(x.target.email)
     
     #email_set = {y.email for x in match_set for y in x.users.all()}   #set()
     
     # Exclude login user
     '''email_set.add(current_user.email)
     for match in match_set:
         email_set.add(match.)'''
     
     gps_reading = fromstr('POINT('+kwargs['latitude']+' '+kwargs['longitude']+')', srid=4326)
     nearest_users = User.geo.exclude(email__in=email_set).exclude(preferences__hidden=True).filter(Q(date_of_birth__gte=min_date) & Q(date_of_birth__lte=max_date))
     nearest_users = nearest_users.filter(gender=gender_pref).filter(location__distance_lte=(gps_reading, D(mi=distance_pref))).distance(gps_reading).order_by('distance')
 
     paginator = PageNumberPagination()
    
     result_page = paginator.paginate_queryset(nearest_users.all(), request)
     
     serializer = UserSerializer(result_page , many=True)
     return paginator.get_paginated_response(serializer.data)
    def get_heatmap_cluster_data(self):
        kursor = connection.cursor()

        grid_size = 0.0005

        kursor.execute(f'''
            SELECT
                COUNT( point ) AS count,
                ST_AsText( ST_Centroid(ST_Collect( point )) ) AS center
            FROM data_allegation
            WHERE
                incident_date >= \'{settings.ALLEGATION_MIN} 00:00:00\'
                AND point IS NOT NULL
            GROUP BY
                ST_SnapToGrid( ST_SetSRID(point, 4326), {grid_size}, {grid_size})
            ''')
        kclusters = kursor.fetchall()
        ret = {'features': [], 'type': 'FeatureCollection'}

        for cluster in kclusters:
            point = fromstr(cluster[1])
            weight = cluster[0]

            allegation_json = {
                'type': 'Feature',
                'properties': {
                    'weight': weight
                },
                'geometry': {
                    'coordinates': [point.x, point.y],
                    'type': 'Point'
                }
            }
            ret['features'].append(allegation_json)

        return json.dumps(ret)
Example #10
0
 def save(self):
     loc = self.address + " " + self.city + ", " + self.state        
     location = urllib.quote_plus(smart_str(loc))
     dd = urllib2.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false" % location).read() 
     ft = simplejson.loads(dd)
     if ft["status"] == 'OK':
         lat = str(ft["results"][0]['geometry']['location']['lat']) 
         lng = str(ft["results"][0]['geometry']['location']['lng'])
         zipcode = None
         for jsonStr in ft["results"][0]['address_components']:
             print jsonStr
             if 'types' in jsonStr:
                 for tp in jsonStr['types']:
                     if tp == " postal_code":
                         zipcode = str.long_name
                         break
         
     print('trying to save!') 
     self.zipcode  = zipcode
     self.lat = lat
     self.lon = lng 
     self.geom = fromstr('POINT('+str(self.lon)+ ' '+str(self.lat)+')', srid=4326)
     
     super(Business, self).save()
Example #11
0
def get_all_nearby(mylat,mylng,distance=1):
    DISTANCE=3
    all_buses = Business.objects.all()
    pnt = fromstr('POINT('+str(mylng)+ ' '+str(mylat)+')', srid=4326)
    nearby_buses =  all_buses.filter(geom__distance_lte=(pnt, D(mi=DISTANCE)))
    return nearby_buses