Esempio n. 1
0
    def post(self, request):
        api_json = {}
        latitude = self.request.data.get('latitude')
        longitude = self.request.data.get('longitude')
        distance = self.request.data.get('distance')

        if latitude and longitude:
            location = GEOSGeometry('POINT({} {})'.format(longitude, latitude),
                                    srid=4326)

        open_space = OpenSpace.objects \
            .filter(polygons__distance_lte=(location, D(km=distance))) \
            .annotate(distance=Distance('polygons', location)) \
            .order_by('distance')

        resource_json = OpenSpaceAttributeSerializer(open_space, many=True)
        json = JSONRenderer().render(resource_json.data)
        stream = io.BytesIO(json)
        data = JSONParser().parse(stream)
        api_json['open_space'] = data
        return Response(api_json)
Esempio n. 2
0
    def get_queryset(self):
        queryset = Clinic.objects.all()

        # basic filter options
        lat = self.request.query_params.get('lat', None)
        lon = self.request.query_params.get('lon', None)
        categories = self.request.query_params.getlist('categories', None)

        if lat and lon:
            try:
                pt = Point(float(lon), float(lat))
            except:
                return Response("Bad point data", status.HTTP_400_BAD_REQUEST)

            queryset = Clinic.objects.distance(pt).order_by('distance')
            queryset.annotate(distance=Distance('location', pt))

        if categories:
            queryset = queryset.filter(clean_categories__contains=categories)

        return queryset
Esempio n. 3
0
    def get(self, request):
        api_json = {}
        count = int(self.request.query_params.get('count'))
        distance = self.request.query_params.get('distance')
        latitude = self.request.query_params.get('latitude')
        longitude = self.request.query_params.get('longitude')
        user_location = GEOSGeometry('POINT({} {})'.format(
            longitude, latitude),
                                     srid=4326)

        resource_queryset = OpenSpace.objects \
                                .filter(polygons__distance_lte=(user_location, D(km=distance))) \
                                .annotate(distance=Distance('polygons', user_location)) \
                                .order_by('distance')[0:count]
        resource_json = OpenSpaceAttributeSerializer(resource_queryset,
                                                     many=True)
        json = JSONRenderer().render(resource_json.data)
        stream = io.BytesIO(json)
        data = JSONParser().parse(stream)
        api_json['open_space'] = data
        return Response(api_json)
Esempio n. 4
0
    def _get_publicbody(self, amenity):
        same_name_pbs = self._get_same_name_pbs(amenity)
        if same_name_pbs and same_name_pbs.count() == 1:
            return same_name_pbs.first()

        nearby_pbs = self._get_nearby_publicbodies(amenity).annotate(
            distance=Distance("geo", amenity.geo)).order_by(
                "-number_of_requests", "distance")

        if nearby_pbs:
            by_name = nearby_pbs.filter(name=amenity.name)
            if by_name:
                return by_name.first()
            if self.kwargs.get('category'):
                by_cat = nearby_pbs.filter(
                    categories__name=self.kwargs['category'])
                if by_cat:
                    return by_cat.first()
            return nearby_pbs.first()

        return super()._get_publicbody(amenity)
Esempio n. 5
0
    def test_distance_geodetic(self):
        """
        Test the `Distance` function on geodetic coordinate systems.
        """
        # Testing geodetic distance calculation with a non-point geometry
        # (a LineString of Wollongong and Shellharbour coords).
        ls = LineString(((150.902, -34.4245), (150.87, -34.5789)), srid=4326)

        # Reference query:
        #  SELECT ST_distance_sphere(point, ST_GeomFromText('LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', 4326))
        #  FROM distapp_australiacity ORDER BY name;
        distances = [
            1120954.92533513, 140575.720018241, 640396.662906304,
            60580.9693849269, 972807.955955075, 568451.8357838,
            40435.4335201384, 0, 68272.3896586844, 12375.0643697706, 0
        ]
        qs = AustraliaCity.objects.annotate(
            distance=Distance('point', ls)).order_by('name')
        for city, distance in zip(qs, distances):
            # Testing equivalence to within a meter.
            self.assertAlmostEqual(distance, city.distance.m, 0)
Esempio n. 6
0
def place_detail(request):
    place_id = request.GET.get('place_id')
    if not place_id:
        return JsonResponse({'error': 'missing place ID'})
    try:
        place = Place.objects.get(place_id=place_id)
    except Place.DoesNotExist:
        return JsonResponse({'error': 'can\'t find place with that ID'})

    nearby = []
    if place.geom:
        nearby = Place.objects.filter(
            Q(geom__distance_lt=(place.geom, D(m=2500)))
            & (Q(gift_card_url__isnull=False) | Q(email_contact__isnull=False))
        ).exclude(place_id=place_id).annotate(
            distance=Distance('geom', place.geom)).order_by('distance')[0:9]

    return JsonResponse({
        'place': place.to_json(),
        'suggestedPlaces': [x.to_json() for x in nearby]
    })
Esempio n. 7
0
def get_nearby_hospital(lng,
                        lat,
                        *,
                        database='tainan',
                        limit=3,
                        distance=5,
                        exclude_fields=None):
    if not exclude_fields:
        exclude_fields = ['hospital_id', 'location', 'objects']

    point = Point(to_float(lng), to_float(lat), srid=4326)
    hospital_set = (Hospital.objects.using(database).annotate(
        distance=Distance('location', point)).filter(
            location__distance_lte=(point,
                                    D(km=5))).order_by('distance')[:limit])

    response_data = [
        model_to_dict(hospital, exclude=exclude_fields)
        for hospital in hospital_set
    ]
    return response_data
Esempio n. 8
0
    def get_context_data(self, **kwargs):
        count = int(self.request.GET.get("count", DEFAULT_COUNT))
        lat = float(self.request.GET.get("lat", DEFAULT_LAT))
        lon = float(self.request.GET.get("lon", DEFAULT_LON))
        user_location = Point(lon, lat, srid=4326)

        print(count, lat, lon)
        
        context = super(ShopListAPIView, self).get_context_data(**kwargs)

        context['shops'] = Shop.objects \
            .annotate(distance=Distance('location', user_location)) \
            .order_by('distance')[0:count]

        context['query'] = {
            'lat': lat,
            'lon': lon,
            'count': count
        }

        return context
Esempio n. 9
0
 def post(self, request, format=None):
     agents = Delivery_Agent.objects.all().filter(on_delivery=False)
     node = Point(float(request.POST['x']),
                  float(request.POST['y']),
                  srid=4326)
     location_list = list()
     agent_list = list()
     selected_agent = Delivery_Agent.objects.annotate(
         distance=Distance('location', node)).order_by('distance').first()
     selected_agent.on_delivery = True
     selected_agent.save()
     delivery = Delivery()
     delivery.customer = Customer.objects.get(user=request.user)
     delivery.delivery_agent = selected_agent
     delivery.pickup_location = node
     delivery.location = selected_agent.location
     delivery.start_time = datetime.datetime.now()
     delivery.total_distance = selected_agent.location.distance(node) * 100
     delivery.save()
     content = {'agent': selected_agent.user.username}
     return Response(content)
Esempio n. 10
0
 def get_queryset(self):
     qs = Establecimiento.objects.all()
     sector_param = self.request.GET.get('sector', '')
     banco_sangre = self.request.GET.get('banco_sangre', '')
     qs = establecimientos_sector(qs, sector_param)
     try:
         lon = float(self.request.query_params.get('lon'))
         lat = float(self.request.query_params.get('lat'))
         distance = float(self.request.query_params.get('distancia', 5))
         point = Point(lon, lat, srid=4326)
         filtro = {
             'location__distance_lte': (point, D(km=distance)),
         }
         if banco_sangre:
             filtro.update({'es_banco_sangre': True})
         qs = qs.annotate(distancia=Distance('location', point)).filter(
             **filtro).order_by('distancia')
     except (ValueError, TypeError) as ex:
         print(ex)
         return []
     return qs
Esempio n. 11
0
    def get(self, request: Request):
        try:
            longitude = float(request.query_params.get('long'))
            latitude = float(request.query_params.get('lat'))
            radius = float(request.query_params.get('r', default=1000))
        except TypeError as e:
            return Response(data={'error': 'Provide valid long and lat.'},
                            status=status.HTTP_400_BAD_REQUEST)

        print(f'Long={longitude}, Lat={latitude}')

        current_coordinate = Point(longitude, latitude, srid=4326)
        stations = StationV2.objects.filter(
            coordinate__dwithin=(current_coordinate, D(m=radius))).annotate(
                distance=Distance('coordinate', current_coordinate)).order_by(
                    'distance')
        # stations = StationV2.objects.all().annotate(
        #     distance=Distance('coordinate', current_coordinate)
        # ).order_by('distance')
        serializer = StationV2Serializer(instance=stations, many=True)
        return Response(data=serializer.data)
    def handle(self, segment, limit=SUGGEST_LIMIT_METERS, *args, **options):

        if segment:
            person_queryset = segment.get_subscribers_queryset()
        else:
            person_queryset = Person.objects.all()

        person_queryset = (
            person_queryset.exclude(coordinates=None).filter(
                role__is_active=True,
                role__last_login__gt=timezone.now() -
                timezone.timedelta(days=60),
            )  # seulement les gens s'étant déjà connectés dans les 2 derniers mois
            .exclude(
                activities__in=Activity.objects.filter(
                    type=Activity.TYPE_EVENT_SUGGESTION,
                    created__gt=timezone.now() - timezone.timedelta(hours=18),
                )
            )  # exclure les personnes ayant déjà reçu une suggestion aujourd'hui
        )

        pbar = tqdm(total=person_queryset.count())
        for person in person_queryset.iterator():
            base_queryset = (Event.objects.with_serializer_prefetch(
                person).listed().upcoming().exclude(coordinates=None))

            near_event = (base_queryset.annotate(
                distance=Distance("coordinates", person.coordinates)).filter(
                    distance__lte=limit).filter(
                        start_time__lt=timezone.now() +
                        timezone.timedelta(days=7)).exclude(attendees=person).
                          distinct().order_by("distance").first())

            if near_event is not None:
                new_event_suggestion_notification(near_event, person)
                # Avoid sending event suggestions via email until stricter rules are defined
                # send_event_suggestion_email.delay(near_event.pk, person.pk)

            pbar.update()
        pbar.close()
Esempio n. 13
0
    def get_queryset(self):

        latitude = self.request.query_params.get('lat', None)
        longitude = self.request.query_params.get('lng', None)
        sort = self.request.query_params.get('sort', None)

        if latitude and longitude:
            # qs = super().get_queryset()
            pnt = GEOSGeometry('POINT(' + str(longitude) + ' ' +
                               str(latitude) + ')',
                               srid=4326)
            new_query = Job.objects.filter(mover_profile=None).annotate(
                distance=Distance('point_a', pnt)).filter(complete=False)\
                .exclude(conflict=True)
            if sort == "price-low":
                return new_query.order_by('distance', 'price')
            elif sort == "price-high":
                return new_query.order_by('distance', '-price')
            elif sort == "dist-low":
                return new_query.order_by('distance', 'trip_distance')
            elif sort == "dist-high":
                return new_query.order_by('distance', '-trip_distance')
            else:
                return new_query.order_by('distance')

        else:
            without_location = Job.objects.filter(mover_profile=None).filter(
                complete=False).exclude(conflict=True)
            sort = self.request.GET.get('sort', '')

            if sort == "price-low":
                return without_location.order_by('price')
            elif sort == "price-high":
                return without_location.order_by('-price')
            elif sort == "dist-low":
                return without_location.order_by('trip_distance')
            elif sort == "dist-high":
                return without_location.order_by('-trip_distance')
            else:
                return without_location.order_by('-created_at')
Esempio n. 14
0
def nearestLamps(request):
    lat = request.query_params.get('lat')
    long = request.query_params.get('long')
    point = Point(
        float(long), float(lat),
        srid=4326)  # we need to use the 4325 srid in order to create the point
    querysets = Lamp.objects.annotate(
        distance=Distance('coord_X_Y', point)).order_by('distance').values(
            'id', 'name', 'station', 'distance')[0:3]
    data = []
    for queryset in querysets:
        data.append({
            "id":
            queryset['id'],
            "name":
            queryset['name'],
            "station":
            queryset['station'],
            'distance':
            transformDistanceValueToFloat(queryset['distance'])
        })
    return Response(json.dumps(data), status=200)
def device_report_api(req):
    report_pincode = req.POST.get('pincode')
    if report_pincode is not None:
        report_pincode=Pincode.objects.filter(pincode=report_pincode).first()
        report_location = Point(x=report_pincode.located_at.x, y=report_pincode.located_at.y, srid=4326)

        suspected_disease = Disease.objects.get(disease_name=req.POST.get("disease_name"))

        closest_hospital = Hospital.objects.annotate(distance=Distance('located_at', report_location)).order_by('distance').first()
        report_source = closest_hospital.user
        public_report = Report(
            source=report_source,
            disease=suspected_disease,
            death=False,
            pincode=report_pincode,
            report_info=req.POST.get('report_info'),
            reported_at=report_location,
            verified=False
        )
        public_report.save()
        return HttpResponse(status=200)
    return HttpResponse(status=500)
Esempio n. 16
0
    def get_queryset(self):
        result = super(ServiceProviderListView, self).get_queryset()

        sesh = self.request.session
        user_geolocation = geolocator.geocode(sesh['address'] + ' ' +
                                              sesh['city'] + ' ' +
                                              sesh['state'] + ' ' +
                                              sesh['zip'])
        user_location = Point(user_geolocation.longitude,
                              user_geolocation.latitude,
                              srid=4326)
        if sesh['sort_distance'] == 'Any':
            miles = 1000
        else:
            miles = sesh['sort_distance']
        #result = ServiceProvider.objects.annotate(distance=Distance("address__location", user_location)).order_by("distance")
        result = ServiceProvider.objects.filter(
            address__location__distance_lte=(user_location, D(
                mi=miles))).annotate(distance=Distance(
                    "address__location", user_location)).order_by("distance")
        #result = ServiceProvider.objects.filter(location__distance_lte=(user_location, D(50000))).annotate(distance=Distance("address__location", user_location)).order_by("distance")
        return result
Esempio n. 17
0
def nearest(request, srid, x, y, format='json'):
    location = Point(float(x), float(y), srid=int(srid))
    set_timeout(format)

    try:
        # Transform to database SRID for comparison (GeometryCentroidDistance does not yet do this)
        location.transform(4326)
    except:
        raise ViewException(format, _('Point outside the area geometry'), 400)

    try:
        # Ordering will be in 'degrees', so fetch a few and sort by actual distance
        postcodes = Postcode.objects.annotate(
            centroid_distance=GeometryCentroidDistance('location', location)
            ).annotate(
                distance=Distance('location', location)
            ).order_by('centroid_distance')[:100]
        postcodes = sorted(postcodes, key=attrgetter('distance'))
        postcode = postcodes[0]
    except DatabaseError as e:
        if 'Cannot find SRID' in e.args[0]:
            raise ViewException(format, e.args[0], 400)
        if 'canceling statement due to statement timeout' not in e.args[0]:
            raise
        raise ViewException(format, 'That query was taking too long to compute.', 500)
    except:
        raise ViewException(format, 'No postcode found near %s,%s (%s)' % (x, y, srid), 404)

    if format == 'html':
        return render(request, 'mapit/postcode.html', {
            'postcode': postcode.as_dict(),
            'json_view': 'mapit-postcode',
        })

    pc = postcode.as_dict()
    pc['distance'] = round(postcode.distance.m)
    return output_json({
        'postcode': pc,
    })
Esempio n. 18
0
 def get_queryset(self):
     """
  Handles a get request of spots
  Params: lat, lng, radius**
  Returns: All spots within given radius of search point.
 """
     radius = self.request.GET.get('radius')
     lat = self.request.GET.get('lat')
     lng = self.request.GET.get('lng')
     if not radius:
         radius = 5
     if lat and lng:
         lattitude = float(lat)
         longitude = float(lng)
         search_point = Point(longitude, lattitude)
         queryset = Spot.objects.filter(
             location__distance_lte=(search_point, D(
                 mi=radius))).annotate(distance=Distance(
                     'location', search_point)).order_by('distance')
     else:
         queryset = []
     return queryset
Esempio n. 19
0
    def form_valid(self, form):
        # Get Data
        latitude = form.cleaned_data['latitude']
        longitude = form.cleaned_data['longitude']

        # get today's & next week's date
        now = timezone.now()
        next_week = now + timezone.timedelta(weeks=1)

        # get location
        location = Point(longitude, latitude, srid=4326)

        # Lookup Events
        events = Event.objects.filter(datetime__gte=now)\
            .filter(datetime__lte=next_week)\
            .annotate(distance=Distance('venue__location', location))\
            .order_by('distance')[0:5]

        # Render the template
        return render(self.request,
                      'gigs/lookup_results.html',
                      context={'events': events})
def marketer_list(request):
    get_copy = request.GET.copy()
    parameters = get_copy.pop("page", True) and get_copy.urlencode()

    filters = request.GET

    marketer_query = PimpUser.objects.filter(usertype=PimpUser.MARKETER, is_active=True)

    marketer_list = MarketerFilter(
        filters, queryset=marketer_query.order_by("-date_joined")
    )

    if request.user.is_authenticated and request.user.is_geolocated:
        marketer_list_with_distance = MarketerFilter(
            filters,
            queryset=marketer_query.annotate(
                distance=Distance("location", request.user.location)
            ).order_by("-date_joined", "distance"),
        )
        marketer_list = marketer_list_with_distance

    # Pagination
    page = request.GET.get("page")
    paginator = Paginator(marketer_list.qs, 12)

    try:
        marketer_list_paginated = paginator.page(page)
    except PageNotAnInteger:
        marketer_list_paginated = paginator.page(1)
    except EmptyPage:
        marketer_list_paginated = paginator.page(paginator.num_pages)

    context = {
        "marketer_list": marketer_list_paginated,
        "marketer_filters": marketer_list,
        "parameters": parameters,
    }

    return render(request, "search/search_marketer.html", context)
Esempio n. 21
0
def view(request, viaje_pk):
    viaje = get_object_or_404(Viaje, pk=viaje_pk)
    if viaje.usuario.pk != request.user.usuario.pk:
        raise Http404("No existe ese viaje.")
    if request.method == 'POST':
        form = RegistroDireccionesForm(request.POST)
        error = ""
        if form.is_valid():
            direccion = form.cleaned_data['direccion']
            longitud = form.cleaned_data['longitud']
            latitud = form.cleaned_data['latitud']
            punto = Point(longitud, latitud)
            bahias = Bahia.objects.filter(
                coordenadas__dwithin=(punto, 100000)).annotate(
                    distance=Distance('coordenadas', punto)).order_by(
                        'distance')
            if bahias.count() > 0:
                bahia = bahias[0]
                destino = Destino.objects.create(direccion=direccion,
                                                 coordenadas=punto,
                                                 bahia=bahia,
                                                 area=bahia.area_set.all()[0],
                                                 viaje=viaje)
                destino.save()
            else:
                error = "No hay ninguna bahía cercana al destino"
        direcciones = viaje.destino_set.all()
        return render(request, 'registrar_direcciones.html', {
            'form': form,
            'direcciones': direcciones,
            'error': error
        })
    elif request.method == 'GET':
        form = RegistroDireccionesForm()
        direcciones = viaje.destino_set.all()
        return render(request, 'registrar_direcciones.html', {
            'form': form,
            'direcciones': direcciones
        })
Esempio n. 22
0
 def tzNameAt(self, latitude, longitude, forceTZ=False):
     '''
     Lookup the timezone name for a given latitude and longitude.
     @latitude: latitude
     @longitude: longitude
     @forceTZ: If forceTZ is true and you can't find a valid timezone return
     the closest timezone you can find instead.
     '''
     point = Point(longitude, latitude, srid=4326)
     zones = Timezone.objects.filter(polygon__contains=point)
     if len(zones):
         return zones[0].name
     elif forceTZ:
         # Return timezone with nearest polygon
         # Limit search to within 2 degrees, otherwise the query takes too long (DWithin makes use of index)
         matches = Timezone.objects\
             .filter(polygon__dwithin=(point, 2))\
             .annotate(distance=Distance('polygon', point))\
             .order_by('distance')
         if len(matches):
             return matches[0].name
         return None
Esempio n. 23
0
    def form_valid(self, form):
        # Get data
        latitude = form.cleaned_data['latitude']
        longitude = form.cleaned_data['longitude']

        # Get today's date
        now = timezone.now()

        # Get next week's date
        next_week = now + timezone.timedelta(weeks=1)

        # Get Point
        location = Point(longitude, latitude, srid=4326)

        # Look up events
        events = Event.objects.filter(datetime__gte=now).filter(
            datetime__lte=next_week).annotate(distance=Distance(
                'venue__location', location)).order_by('distance')[0:5]

        # Render the template
        return render_to_response('gigs/lookupresults.html',
                                  {'events': events})
Esempio n. 24
0
 def geo_intersects(self, geom):
     point_filter = Q(geom_point__isnull=False) & Q(
         geom_point__intersects=geom)
     line_filter = Q(geom_linestring__isnull=False) & Q(
         geom_linestring__intersects=geom)
     polygon_filter = Q(geom_polygon__isnull=False) & Q(
         geom_polygon__intersects=geom)
     return self.filter(
         Q(point_filter) | Q(line_filter)
         | Q(polygon_filter)).annotate(distance=Distance(
             geom,
             Case(
                 When(geom_linestring__isnull=True,
                      geom_polygon__isnull=True,
                      then='geom_point'),
                 When(geom_point__isnull=True,
                      geom_polygon__isnull=True,
                      then=PointOnSurface('geom_linestring')),
                 When(geom_point__isnull=True,
                      geom_linestring__isnull=True,
                      then=PointOnSurface('geom_polygon'))))).order_by(
                          'distance')
Esempio n. 25
0
def myTrainings(request):
    # get all user trainings
    athlete = Athlete.objects.get(user=request.user)
    myTrainings = athlete.trainings.all()
    myTrainings = filterPastDates(myTrainings, "all")

    user_location_point = createUserLocationPoint(locationString)
    mapFolium = createMapWithUserLocationMark(user_location_point)

    #add marker to locations
    [training.putOnMap(mapFolium) for training in myTrainings]
    mapFolium = mapFolium._repr_html_()

    # order by distance to user
    distanceSet = myTrainings.annotate(distance=Distance(
        'location', user_location_point)).order_by('distance').values(
            'id', 'adress', 'sport', 'date', 'distance')

    return render(request, "trainings/myTrainings.html", {
        "distanceSet": distanceSet,
        "map": mapFolium,
    })
Esempio n. 26
0
    def form_valid(self, form):
        # Get data
        latitude = form.cleaned_data['latitude']
        longitude = form.cleaned_data['longitude']

        # Get today's date
        now = timezone.now()

        # Get next week's date
        next_week = now + timezone.timedelta(weeks=1)

        # Get Point
        location = Point(longitude, latitude, srid=4326)

        # Look up topics
        topics = Topic.objects.filter(datetime__gte=now).filter(
            datetime__lte=next_week).annotate(distance=Distance(
                'suburb__location', location)).order_by('distance')[0:5]

        # Render the template
        return render_to_response('burbnews/topic_list.html',
                                  {'topics': topics})
Esempio n. 27
0
    def get_queryset(self):
        zipcode_string = self.request.query_params.get('zipcode', None)

        if zipcode_string is None:
            raise serializers.ValidationError('A zipcode must be provided.')

        try:
            zipcode = int(zipcode_string)
        except ValueError as value_error:
            raise serializers.ValidationError(
                f'Zipcode is in an invalid format and could not be parsed: {value_error}'
            )

        reporting_area_location = AirNowReportingAreaZipCode.objects.filter(
            zipcode=zipcode).first()

        if reporting_area_location is None:
            # no exact match, we'll look for the nearest reporting area to the zip code centroid.
            country = pgeocode.Nominatim('us')
            locale = country.query_postal_code(zipcode)

            longitude = locale['longitude']
            latitude = locale['latitude']

            if not isinstance(locale,
                              Series) or isnull(longitude) or isnull(latitude):
                raise NotFound(f'No location found for {zipcode}.')

            zipcode_center = Point(longitude, latitude, srid=4236)
            reporting_area = AirNowReportingArea.objects.annotate(
                distance=Distance('location', zipcode_center)).order_by(
                    'distance').first()
        else:
            reporting_area = AirNowReportingArea.objects.filter(
                name=reporting_area_location.city,
                state_code=reporting_area_location.state).first()

        return AirNowObservation.objects.filter(reporting_area=reporting_area)
Esempio n. 28
0
 def geo_distance(self, latlon, radius):
     geom = Point(latlon[1], latlon[0])
     point_filter = Q(geom_point__isnull=False) & Q(
         geom_point__distance_lte=(geom, D(m=radius)))
     line_filter = Q(geom_linestring__isnull=False) & Q(
         geom_linestring__distance_lte=(geom, D(m=radius)))
     polygon_filter = Q(geom_polygon__isnull=False) & Q(
         geom_polygon__bbcontains=geom) & Q(geom_polygon__contains=geom)
     return self.filter(
         Q(point_filter) | Q(line_filter)
         | Q(polygon_filter)).annotate(distance=Distance(
             geom,
             Case(
                 When(geom_linestring__isnull=True,
                      geom_polygon__isnull=True,
                      then='geom_point'),
                 When(geom_point__isnull=True,
                      geom_polygon__isnull=True,
                      then=PointOnSurface('geom_linestring')),
                 When(geom_point__isnull=True,
                      geom_linestring__isnull=True,
                      then=PointOnSurface('geom_polygon'))))).order_by(
                          'distance')
Esempio n. 29
0
    def get(self, request, *args, **kwargs):
        postcode = request.query_params.get('postcode')
        range_distance = request.query_params.get('range_distance')

        if postcode and range_distance:
            # Normalise postcode first
            postcode = postcode.replace(' ', '').upper()

            try:
                codepoint = CodePoint.objects.get(postcode=postcode)
            except CodePoint.DoesNotExist as ex:
                return Response(
                    'The given postcode is not available in CodePoints',
                    status=status.HTTP_400_BAD_REQUEST)

            locations = Location.objects.filter(
                geom__dwithin=(codepoint.point, D(m=range_distance))).\
                annotate(distance=Distance('geom', codepoint.point))
            serializer = LocationSerializer(locations, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response('The postcode parameter is missing',
                            status=status.HTTP_400_BAD_REQUEST)
Esempio n. 30
0
 def fetch_users(self, request):
     user_1_reference_id = request.user.reference_id
     last_user_location = UserLocation.objects.filter(users__reference_id=user_1_reference_id).order_by('-created_at')[0]["location"]
     queryset = UserLocation.objects.order_by('-created_at').distinct()
     queryset = queryset.exclude(users__reference_id=user_1_reference_id)
     user_1_preferred = User.objects.get(reference_id=user_1_reference_id).looking_for
     ## Filter out people based on user's preference.
     if user_1_preferred is "MF" or "FM":
         pass
     else:
         queryset = queryset.filter(users__gender=user_1_preferred)
         
     queryset = queryset.annotate(distance=Distance('location', last_user_location)).order_by('distance')[0:100]
     final_list = []
     context = {}
     for item in queryset:
         context['id'] = item['id']
         context['reference_id'] = item['reference_id']
         context['user_id'] = item['users__reference_id']
         context['distance'] = item['distance']
         final_list.append(context)
         context = {}
     return Response(final_list, status=200)