Python django.contrib.gis.measure.D Examples

The following are 16 code examples of django.contrib.gis.measure.D(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.gis.measure , or try the search function .
Example #1
Source File: widgets.py    From cornerwise with MIT License 6 votes vote down vote up
def __init__(self, *args, min_value=D(m=10), max_value=D(m=100),
                 initial_unit="ft", **kwargs):
        error_messages = {
            "incomplete": "Enter a distance"
        }
        self.min_value = min_value
        self.max_value = max_value
        fields = (
            FloatField(),
            ChoiceField(choices=self.DISTANCE_UNITS,
                        initial=initial_unit)
        )
        super().__init__(
            fields=fields,
            error_messages=error_messages,
            require_all_fields=True,
            *args, **kwargs
        )
        self.widget = DistanceWidget(choices=self.DISTANCE_UNITS) 
Example #2
Source File: tests.py    From cornerwise with MIT License 6 votes vote down vote up
def test_site_restrictions(self):
        """
        Check that site-specific constraints are checked.
        """
        subscription = models.Subscription(
            site_name="somerville.cornerwise.gov")
        query = add_radius({})
        query["r"] = D(ft=10000).m

        with self.assertRaises(ValidationError):
            subscription.set_validated_query(query)

        with self.assertRaises(ValidationError):
            subscription.set_validated_query(add_box({}))

        query["r"] = "300m"
        query["region_name"] = "Tunguska, Krasnoyarsk Krai"

        with self.assertRaises(ValidationError):
            subscription.set_validated_query(query) 
Example #3
Source File: models.py    From cornerwise with MIT License 6 votes vote down vote up
def readable_query(query, unit="ft"):
        # NOTE Not currently used, but may be useful again in the future
        if "projects" in query:
            if query["project"] == "all":
                desc = "Public proposals "
            else:
                desc = "Private proposals "
        else:
            desc = "All proposals "

        if "text" in query:
            desc += "matching \"" + query["text"] + "\" "

        if "box" in query:
            box = bounds_from_box(query["box"])
            sw, ne = poly_bounds(box)
            desc += "".join(["inside the region: ",
                             prettify_point(sw), " and ", prettify_point(ne)])
        elif "center" in query:
            dist = D(m=query["r"])

        return desc 
Example #4
Source File: geo.py    From jorvik with GNU General Public License v3.0 6 votes vote down vote up
def nel_raggio(self, ricerca):
        """
        Filtra una ricerca, per gli elementi nel raggio di questo elemento.
        :return: La ricerca filtrata
        """
        from formazione.models import CorsoBase

        if not self.locazione:
            # Check per restituire <QuerySet> dello stesso tipo di oggetto <ricerca>
            if ricerca.model is CorsoBase:
                return CorsoBase.objects.none()

            return self.__class__.objects.none()

        q = ricerca.filter(locazione__geo__distance_lte=(self.locazione.geo, D(km=self.raggio)))
        return q 
Example #5
Source File: widgets.py    From cornerwise with MIT License 5 votes vote down vote up
def decompress(self, distance):
        if not isinstance(distance, D):
            distance = D(ft=distance)
        return [distance.ft, distance._default_unit] 
Example #6
Source File: widgets.py    From cornerwise with MIT License 5 votes vote down vote up
def compress(self, values):
        return D(**{values[1]: values[0]}) 
Example #7
Source File: staff_notifications.py    From cornerwise with MIT License 5 votes vote down vote up
def get_subscribers(geocoded=[], proposals=[],
                    region=settings.GEO_REGION,
                    notify_radius=D(ft=300)):
    """Get the Subscriptions that should be informed about the given geocoded
    addresses and/or proposals. Returns a dictionary of Subscriptions to
    (address/proposal, Point).

    :param geocoded: a list of tuples (address, Point, formatted_address)
    :param proposals: a list of Proposals

    """
    if not isinstance(notify_radius, D):
        notify_radius = D(ft=notify_radius)

    def unpack(x):
        return (x, x.location) if isinstance(x, Proposal) else (x[0], x[1])

    sub_near = defaultdict(list)
    for thing, point in map(unpack, chain(proposals, geocoded)):
        if notify_radius:
            subs = Subscription.objects.filter(
                center__distance_lte=(point, notify_radius))
        else:
            subs = Subscription.objects.containing(point)

        for sub in subs:
            sub_near[sub].append((thing, point))

    return sub_near 
Example #8
Source File: utils.py    From cornerwise with MIT License 5 votes vote down vote up
def distance_from_str(distance):
    if isinstance(distance, str):
        m = re.match(distance_patt, distance)
        if m:
            unit = m.group(2) or "m"
            return D(**{unit: float(m.group(1))})
    else:
        return D(m=float(distance)) 
Example #9
Source File: models.py    From cornerwise with MIT License 5 votes vote down vote up
def area_description(self, dist_units="ft"):
        if self.box:
            sw, ne = poly_bounds(self.box)
            return ("inside the region bounded by "
                    f"{prettify_point(sw)} and {prettify_point(ne)}")

        if self.center:
            dist = round(getattr(D(m=self.radius), dist_units))
            return "within {dist} {dist_units} of {where}".format(
                dist=dist,
                dist_units=dist_units,
                where=(self.address or prettify_point(self.center))
            ) 
Example #10
Source File: utils.py    From Disfactory with MIT License 5 votes vote down vote up
def _get_nearby_factories(latitude, longitude, radius):
    """Return nearby factories based on position and search range."""
    # NOTE: if we use h3 for geoencoding in the future, we can use h3.k_ring():
    # ref: https://observablehq.com/@nrabinowitz/h3-radius-lookup
    pnt = Point(x=longitude, y=latitude, srid=4326)
    pnt.transform(settings.POSTGIS_SRID)
    ids = Factory.objects.only("id").filter(point__distance_lte=(pnt, D(km=radius)))
    if len(ids) > settings.MAX_FACTORY_PER_GET:
        ids = _sample(ids, settings.MAX_FACTORY_PER_GET)
    return Factory.objects.filter(id__in=[obj.id for obj in ids]) 
Example #11
Source File: test_utils.py    From Disfactory with MIT License 5 votes vote down vote up
def test_get_nearby_factories_called_db_correctlly(self):
        lat = 25
        lng = 120
        radius = 2.  # km
        pnt = Point(x=lng, y=lat, srid=4326)
        pnt.transform(3857)
        d = D(km=radius)
        # with patch("api.views.utils.Factory.objects.filter") as mock_filter:
        #     _get_nearby_factories(lat, lng, radius=radius)
        #     mock_filter.assert_called_once_with(point__distance_lte=(pnt, d)) 
Example #12
Source File: test_models.py    From Disfactory with MIT License 5 votes vote down vote up
def test_migration_seed_data_correctly(self):
        pnt = Point(x=120.1, y=23.234, srid=4326)
        pnt.transform(3857)
        factories = Factory.objects.filter(point__distance_lte=(pnt, D(km=1)))
        self.assertEqual(set([factory.name for factory in factories]), set([
            "既有違章工廠 No.2",
            "既有違章工廠 No.3",
            "既有違章工廠 No.8",
            "既有違章工廠 No.9",
            "既有違章工廠 No.10",
            "既有違章工廠 No.11",
            "既有違章工廠 No.12",
            "既有違章工廠 No.13",
            "既有違章工廠 No.22",
        ])) 
Example #13
Source File: models.py    From cykel with MIT License 5 votes vote down vote up
def end(self, end_position=None):
        self.rent_end = now()
        if end_position is not None:
            self.end_position = end_position
        elif self.bike.public_geolocation():
            self.end_position = self.bike.public_geolocation().geo
        self.save()

        if self.end_position:
            # attach bike to station if location is closer than X meters
            # distance is configured in preferences
            max_distance = preferences.BikeSharePreferences.station_match_max_distance
            station_closer_than_Xm = Station.objects.filter(
                location__distance_lte=(self.end_position, D(m=max_distance)),
                status="AC",
            ).first()
            if station_closer_than_Xm:
                self.bike.current_station = station_closer_than_Xm
                self.end_station = station_closer_than_Xm
                self.save()
            else:
                self.bike.current_station = None

        # set Bike status back to available
        self.bike.availability_status = "AV"
        self.bike.save()
        try:
            # set new non static bike ID, so for GBFS observers can not track this bike
            self.bike.non_static_bike_uuid = uuid.uuid4()
            self.bike.save()
        except IntegrityError:
            # Congratulations! The 2^64 chance of uuid4 collision has happend.
            # here coul'd be the place for the famous comment: "should never happen"
            # So we catch this error here, but don't handle it.
            # because don't rotating a uuid every 18,446,744,073,709,551,615 rents is ok
            pass 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test02_distance_lookup(self):
        "Testing distance lookup support on non-point geography fields."
        z = Zipcode.objects.get(code='77002')
        cities1 = list(City.objects
                       .filter(point__distance_lte=(z.poly, D(mi=500)))
                       .order_by('name')
                       .values_list('name', flat=True))
        cities2 = list(City.objects
                       .filter(point__dwithin=(z.poly, D(mi=500)))
                       .order_by('name')
                       .values_list('name', flat=True))
        for cities in [cities1, cities2]:
            self.assertEqual(['Dallas', 'Houston', 'Oklahoma City'], cities) 
Example #15
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test02_distance_lookup(self):
        "Testing distance lookup support on non-point geography fields."
        z = Zipcode.objects.get(code='77002')
        cities1 = list(City.objects
                       .filter(point__distance_lte=(z.poly, D(mi=500)))
                       .order_by('name')
                       .values_list('name', flat=True))
        cities2 = list(City.objects
                       .filter(point__dwithin=(z.poly, D(mi=500)))
                       .order_by('name')
                       .values_list('name', flat=True))
        for cities in [cities1, cities2]:
            self.assertEqual(['Dallas', 'Houston', 'Oklahoma City'], cities) 
Example #16
Source File: views.py    From cykel with MIT License 4 votes vote down vote up
def updatebikelocation(request):
    device_id = request.data.get("device_id")
    if not (device_id):
        return Response({"error": "device_id missing"}, status=400)
    try:
        tracker = LocationTracker.objects.get(device_id=device_id)
    except LocationTracker.DoesNotExist:
        return Response({"error": "tracker does not exist"}, status=404)

    serializer = LocationTrackerUpdateSerializer(tracker, data=request.data)
    if not serializer.is_valid():
        return Response(serializer.errors, status=400)

    serializer.save()

    lat = request.data.get("lat")
    lng = request.data.get("lng")
    accuracy = request.data.get("accuracy")
    loc = None

    if lat and lng:
        loc = Location.objects.create(source="TR", reported_at=now())
        if tracker.bike:
            loc.bike = tracker.bike
        loc.geo = Point(float(lng), float(lat), srid=4326)
        loc.tracker = tracker
        if accuracy:
            loc.accuracy = accuracy
        loc.save()

    if tracker.bike:
        bike = tracker.bike
        bike.last_reported = now()

        if loc:
            # check if bike is near station and assign it to that station
            # distance ist configured in prefernces
            max_distance = preferences.BikeSharePreferences.station_match_max_distance
            station_closer_than_Xm = Station.objects.filter(
                location__distance_lte=(loc.geo, D(m=max_distance)), status="AC"
            ).first()
            if station_closer_than_Xm:
                bike.current_station = station_closer_than_Xm
            else:
                bike.current_station = None

        bike.save()

    if not loc:
        return Response({"success": True, "warning": "lat/lng missing"})

    return Response({"success": True})