Python django.contrib.gis.geos.Point() Examples

The following are 30 code examples of django.contrib.gis.geos.Point(). 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.geos , or try the search function .
Example #1
Source File: SiteSerializer.py    From kobo-predict with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def update(self, instance, validated_data):
        data = self.context['request'].data
        type_id = data.pop('type')
        site_type = ProjectType.objects.get(pk=type_id)
        verify_survey = data.pop('is_survey')
        if verify_survey:
            validated_data.update({'is_survey': False})
            validated_data.update({'is_active': True})
        else:
            validated_data.update({'is_survey': True})
            validated_data.update({'is_active': False})

        p = Point(float(validated_data.pop('longitude')), float(validated_data.pop('latitude')), srid=4326)
        validated_data.update({'location':p})
        Site.objects.filter(pk=instance.pk).update(**validated_data)
        site = Site.objects.get(pk=instance.id)
        site.type = site_type
        site.save()
        return site 
Example #2
Source File: test_api.py    From openwisp-controller with GNU General Public License v3.0 6 votes vote down vote up
def test_put_update_coordinates(self):
        self.assertEqual(self.location_model.objects.count(), 0)
        dl = self._create_object_location()
        url = reverse(self.url_name, args=[dl.device.pk])
        url = '{0}?key={1}'.format(url, dl.device.key)
        self.assertEqual(self.location_model.objects.count(), 1)
        coords = json.loads(Point(2, 23).geojson)
        feature = json.dumps({'type': 'Feature', 'geometry': coords})
        r = self.client.put(url, feature, content_type='application/json')
        self.assertEqual(r.status_code, 200)
        self.assertDictEqual(
            r.json(),
            {
                'type': 'Feature',
                'geometry': coords,
                'properties': {'name': dl.location.name},
            },
        )
        self.assertEqual(self.location_model.objects.count(), 1) 
Example #3
Source File: upsert_timetable_data.py    From bus-shaming with MIT License 6 votes vote down vote up
def process_stops(feed, csvreader):
    print('Processing stops')
    existing = {}
    for stop in Stop.objects.filter(feed=feed):
        existing[stop.gtfs_stop_id] = stop

    for row in csvreader:
        gtfs_stop_id = row['stop_id']
        stop = existing.get(gtfs_stop_id, None)
        changed = False
        values = {}
        values['name'] = row['stop_name']
        x = float(row['stop_lon'])
        y = float(row['stop_lat'])
        values['position'] = Point(x, y, srid=4326)
        if stop is None:
            stop = Stop(feed=feed, gtfs_stop_id=gtfs_stop_id)
            changed = True
        for value in values:
            prev = getattr(stop, value)
            if prev != values[value]:
                setattr(stop, value, values[value])
                changed = True
        if changed:
            stop.save() 
Example #4
Source File: models.py    From cornerwise with MIT License 6 votes vote down vote up
def make_property_map():
    def _g(p, default=UNSET):
        return lambda d: d.get(p, default)

    def _G(p):
        return lambda d: d[p]

    def get_other_addresses(d):
        return ";".join(d["all_addresses"][1:]) if "all_addresses" in d else ""

    return [("address", lambda d: d["all_addresses"][0]),
            ("other_addresses", get_other_addresses),
            ("location", lambda d: Point(d["location"]["long"], d["location"]["lat"])),
            ("summary", lambda d: d["summary"][0:1024] if "summary" in d else UNSET),
            ("description", _g("description")),
            ("source", _g("source")),
            ("region_name", _g("region_name")),
            ("complete", _g("complete")),
            ("status", _g("status"))] 
Example #5
Source File: utils.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def geocode(query, country='', private=False, annotations=False, multiple=False):
    key = SiteConfiguration.get_solo().opencage_api_key
    lang = settings.LANGUAGE_CODE
    if not query:
        return
    params = {'language': lang}
    if not annotations:
        params.update({'no_annotations': int(not annotations)})
    if private:
        params.update({'no_record': int(private)})
    if country:
        params.update({'countrycode': country})
    result = geocoder.opencage(query, key=key, params=params, maxRows=15 if multiple else 1)
    logging.getLogger('PasportaServo.geo').debug(
        "Query: %s\n\tResult: %s\n\tConfidence: %d", query, result, result.confidence)
    result.point = Point(result.xy, srid=SRID) if result.xy else None
    return result 
Example #6
Source File: instance.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _set_geom(self):
        xform = self.xform
        data_dictionary = xform.data_dictionary()
        geo_xpaths = data_dictionary.geopoint_xpaths()
        doc = self.get_dict()
        points = []

        if len(geo_xpaths):
            for xpath in geo_xpaths:
                geometry = [float(s) for s in doc.get(xpath, u'').split()]

                if len(geometry):
                    lat, lng = geometry[0:2]
                    points.append(Point(lng, lat))

            if not xform.instances_with_geopoints and len(points):
                xform.instances_with_geopoints = True
                xform.save()

            self.geom = GeometryCollection(points) 
Example #7
Source File: forms.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        is_new = kwargs.pop('new', None)
        org_id = kwargs.pop('organization_id', None)
        super(ProjectForm, self).__init__(*args, **kwargs)

        if not self.fields['location'].initial:
            self.fields['location'].initial = Point(85.3240, 27.7172,srid=4326)
        self.fields['type'].empty_label = None
        self.fields['cluster_sites'].label = "Do you want to cluster sites in this Project?"
        #self.fields['organization'].empty_label = None

        if not is_new:
            org_id = kwargs['instance'].organization.id
        self.fields['geo_layers'].queryset = GeoLayer.objects.filter(
            organization__id=org_id
        ) 
Example #8
Source File: imports.py    From gazetteer with MIT License 6 votes vote down vote up
def import_gazetteer(f, limit):
    t = csv.reader(f, delimiter="\t")
    i = 0
    for row in t:
        ft = Feature()
        if Feature.objects.filter(url=row[0]).count() > 0:
            print "duplicate row " + row[0]
        else:
            ft.url = row[0]
            ft.preferred_name = row[1]

            try:
                fcode = FeatureType.objects.get(code=row[2])
            except:
                fcode = None

            ft.feature_type = fcode
            ft.admin1 = row[4]
            ft.admin2 = row[5]
            ft.geometry = Point(float(row[7]), float(row[6]))
            ft.save()
            print "saved " + ft.preferred_name
            i += 1
            if i > limit:
                break 
Example #9
Source File: views.py    From semillas_platform with MIT License 5 votes vote down vote up
def get_queryset(self):
        queryset = Service.objects.all()
        # Order all the services by distance to the requester user location
        if 'lat' in self.request.query_params and 'lon' in self.request.query_params:
            # Brings lat and lon in request parameters
            ref_location = Point(float(self.request.query_params['lon']), float(
                self.request.query_params['lat']), srid=4326)
            if not self.request.user.is_anonymous and \
                    not self.request.user.location_manually_set:
                # If user is logged in, save his location
                self.request.user.location = ref_location
                self.request.user.save()
        elif not self.request.user.is_anonymous and (self.request.user.location is not None):
            # User has a location previously saved
            ref_location = self.request.user.location
        else:
            # if no location at all
            geoip = GeoIP2()
            ip = self.request.META['REMOTE_ADDR']
            try:
                ref_location = Point(geoip.lon_lat(ip), srid=4326)
            except AddressNotFoundError:
                logger.warning('Location could not been retrieved by any mean')
                ref_location = Point((-3.8196228, 40.4378698), srid=4326)  # Madrid
            if not self.request.user.is_anonymous:
                self.request.user.location = ref_location
                self.request.user.save()
        return queryset.annotate(dist=Distance('author__location', ref_location)).order_by('dist') 
Example #10
Source File: views.py    From tracker_project with MIT License 5 votes vote down vote up
def form_valid(self, form):
        form.instance.location = Point(
            (float(form.cleaned_data['location_lon']), float(form.cleaned_data['location_lat']))
        )

        return super(ReportIncidentView, self).form_valid(form) 
Example #11
Source File: test_fields.py    From drf-extra-fields with Apache License 2.0 5 votes vote down vote up
def test_create(self):
        """
        Test for creating Point field in the server side
        """
        now = datetime.datetime.now()
        point = {
            "latitude": 49.8782482189424,
            "longitude": 24.452545489
        }
        serializer = PointSerializer(data={'created': now, 'point': point})
        saved_point = SavePoint(point=point, created=now)
        self.assertTrue(serializer.is_valid())
        self.assertEqual(serializer.validated_data['created'], saved_point.created)
        self.assertFalse(serializer.validated_data is saved_point) 
Example #12
Source File: test_fields.py    From drf-extra-fields with Apache License 2.0 5 votes vote down vote up
def test_serialization(self):
        """
        Regular JSON serialization should output float values
        """
        from django.contrib.gis.geos import Point
        now = datetime.datetime.now()
        point = Point(24.452545489, 49.8782482189424)
        saved_point = SavePoint(point=point, created=now)
        serializer = PointSerializer(saved_point)
        self.assertEqual(serializer.data['point'], {'latitude': 49.8782482189424, 'longitude': 24.452545489}) 
Example #13
Source File: test_fields.py    From drf-extra-fields with Apache License 2.0 5 votes vote down vote up
def test_str_points_serialization(self):
        """
        PointField with str_points=True should output string values
        """
        from django.contrib.gis.geos import Point
        now = datetime.datetime.now()
        # test input is shortened due to string conversion rounding
        # gps has at max 8 decimals, so it doesn't make a difference
        point = Point(24.452545489, 49.8782482189)
        saved_point = SavePoint(point=point, created=now)
        serializer = StringPointSerializer(saved_point)
        self.assertEqual(serializer.data['point'], {'latitude': '49.8782482189', 'longitude': '24.452545489'})


# Backported from django_rest_framework/tests/test_fields.py 
Example #14
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def geos(self, query):
        "Returns a GEOS Point object for the given query."
        ll = self.lon_lat(query)
        if ll:
            from django.contrib.gis.geos import Point
            return Point(ll, srid=4326)
        else:
            return None

    # #### GeoIP Database Information Routines #### 
Example #15
Source File: test_api_updatebikelocation.py    From cykel with MIT License 5 votes vote down vote up
def active_station():
    return Station.objects.create(
        status="AC",
        station_name="Station McStationface",
        location=Point(9.99024, 48.39662, srid=4326),
    ) 
Example #16
Source File: archivehistory.py    From tw-rental-house-data with MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, UUID):
            # if the obj is uuid, we simply return the value of uuid
            return obj.hex
        if isinstance(obj, datetime):
            return obj.isoformat()
        if isinstance(obj, Point):
            return obj.coords
        return json.JSONEncoder.default(self, obj) 
Example #17
Source File: views.py    From cykel with MIT License 5 votes vote down vote up
def finish_rent(request):
    lat = request.data.get("lat")
    lng = request.data.get("lng")
    rent_id = request.data.get("rent_id")
    try:
        rent = Rent.objects.get(id=rent_id)
    except Rent.DoesNotExist:
        return Response(
            {"error": "rent does not exist"}, status=status.HTTP_404_NOT_FOUND
        )

    if rent.user != request.user:
        return Response(
            {"error": "rent belongs to another user"},
            status=status.HTTP_403_PERMISSON_DENIED,
        )
    if rent.rent_end is not None:
        return Response(
            {"error": "rent was already finished"}, status=status.HTTP_410_GONE
        )

    end_position = None
    if lat and lng:
        loc = Location.objects.create(bike=rent.bike, source="US", reported_at=now())
        loc.geo = Point(float(lng), float(lat), srid=4326)
        loc.save()
        end_position = loc.geo

    rent.end(end_position)

    return Response({"success": True}) 
Example #18
Source File: 0011_auto_20190911_1936.py    From cykel with MIT License 5 votes vote down vote up
def move_bike_position_to_location(apps, schema_editor):
    Bike = apps.get_model("bikesharing", "Bike")
    Location = apps.get_model("bikesharing", "Location")
    for bike in Bike.objects.all():
        loc = Location.objects.create(
            bike=bike,
            geo=bike.current_position,
            source="LO",
            reported_at=bike.last_reported,
        )
        loc.save()
        bike.current_position = Point(0, 0, srid=4326)
        bike.save() 
Example #19
Source File: test_api_gbfs.py    From cykel with MIT License 5 votes vote down vote up
def active_station():
    return Station.objects.create(
        status="AC",
        station_name="Station McStationface",
        location=Point(9.99024, 48.39662, srid=4326),
        max_bikes=5,
    ) 
Example #20
Source File: test_gis_fields.py    From django-GDPR with MIT License 5 votes vote down vote up
def test_point_base(self):
        from django.contrib.gis.geos import Point

        point = Point(1, 1)
        out = self.field.get_encrypted_value(point, self.encryption_key)

        self.assertNotEqual(point.tuple, out.tuple)

        out_decrypted = self.field.get_decrypted_value(out, self.encryption_key)

        self.assertTupleEqual(point.tuple, out_decrypted.tuple) 
Example #21
Source File: gis.py    From django-GDPR with MIT License 5 votes vote down vote up
def get_decrypted_value(self, value, encryption_key: str):
        if not is_gis_installed():
            raise ImproperlyConfigured('Unable to load django GIS.')
        from django.contrib.gis.geos import Point

        new_val: Point = Point(value.tuple)
        new_val.x = (new_val.x - self.get_numeric_encryption_key(encryption_key, int(new_val.x))) % self.max_x_range
        new_val.y = (new_val.y - self.get_numeric_encryption_key(encryption_key, int(new_val.y))) % self.max_y_range

        return new_val 
Example #22
Source File: gis.py    From django-GDPR with MIT License 5 votes vote down vote up
def get_encrypted_value(self, value, encryption_key: str):
        if not is_gis_installed():
            raise ImproperlyConfigured('Unable to load django GIS.')
        from django.contrib.gis.geos import Point

        new_val: Point = Point(value.tuple)
        new_val.x = (new_val.x + self.get_numeric_encryption_key(encryption_key, int(new_val.x))) % self.max_x_range
        new_val.y = (new_val.y + self.get_numeric_encryption_key(encryption_key, int(new_val.y))) % self.max_y_range

        return new_val 
Example #23
Source File: gis.py    From django-GDPR with MIT License 5 votes vote down vote up
def is_gis_installed():
    try:
        from django.contrib.gis.geos import Point
        return True
    except ImproperlyConfigured:
        return False 
Example #24
Source File: test_query.py    From django-spillway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_summarize_point(self):
        qs = self.qs.summarize(geos.Point(-9999, -9999))
        self.assertEqual(list(qs[0].image), [])
        self.assertEqual(list(qs.get(pk=1).image), [])
        self.assertRaises(TypeError, qs.summarize, (1, 1)) 
Example #25
Source File: models.py    From django-spillway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_buffer(cls, coord, radius, **data):
        return cls.create(geom=geos.Point(*coord).buffer(radius), **data) 
Example #26
Source File: query.py    From django-spillway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tile(self, bbox, z=0, format=None, clip=True):
        """Returns a GeoQuerySet intersecting a tile boundary.

        Arguments:
        bbox -- tile extent as geometry
        Keyword args:
        z -- tile zoom level used as basis for geometry simplification
        format -- vector tile format as str (pbf, geojson)
        clip -- clip geometries to tile boundary as boolean
        """
        # Tile grid uses 3857, but GeoJSON coordinates should be in 4326.
        tile_srid = 3857
        bbox = getattr(bbox, 'geos', bbox)
        clone = filter_geometry(self, intersects=bbox)
        field = clone.geo_field
        srid = field.srid
        sql = field.name
        try:
            tilew = self.tilewidths[z]
        except IndexError:
            tilew = self.tilewidths[-1]
        if bbox.srid != srid:
            bbox = bbox.transform(srid, clone=True)
        # Estimate tile width in degrees instead of meters.
        if bbox.srs.geographic:
            p = geos.Point(tilew, tilew, srid=tile_srid)
            p.transform(srid)
            tilew = p.x
        if clip:
            bufbox = bbox.buffer(tilew)
            sql = geofn.Intersection(sql, bufbox.envelope)
        sql = SimplifyPreserveTopology(sql, tilew)
        if format == 'pbf':
            return clone.pbf(bbox, geo_col=sql)
        sql = geofn.Transform(sql, 4326)
        return clone.annotate(**{format: sql}) 
Example #27
Source File: forms.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean(self):
        lat = self.data.get("Longitude","85.3240")
        long = self.data.get("Latitude","27.7172")
        p = Point(round(float(lat), 6), round(float(long), 6),srid=4326)
        self.cleaned_data["location"] = p
        super(OrganizationForm, self).clean() 
Example #28
Source File: test_importers.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_import_locations_only(self):
        importer = xls.XLSImporter(
            project=self.project, path=self.path + self.valid_xls)
        config = {
            'file': self.path + self.valid_xls,
            'type': 'xls',
            'entity_types': ['SU'],
            'location_type_field': 'type',
            'geometry_field': 'geometry.ewkt',
            'attributes': self.location_attributes,
            'project': self.project,
            'allowed_location_types': [choice[0] for choice in TYPE_CHOICES]
        }
        importer.import_data(config)
        assert Party.objects.all().count() == 0
        assert SpatialUnit.objects.all().count() == 10
        assert TenureRelationship.objects.all().count() == 0
        for su in SpatialUnit.objects.filter(project_id=self.project.pk).all():
            if su.geometry is not None:
                assert type(su.geometry) is Point

        # test spatial unit attribute creation
        sus = SpatialUnit.objects.filter(
            attributes__contains={'nid_number': '3913647224045'})
        assert len(sus) == 1
        su = sus[0]
        assert len(su.attributes) == 20
        assert 'how_aquire_landwh' not in su.attributes.keys()
        assert 'how_aquire_landw' in su.attributes.keys()
        assert su.attributes[
            'others_conflict'] == ('কিছু বেখলে অাছে জোর করে দখল করে ভোগ করে '
                                   'অন্য জমির মালক।')
        assert su.attributes['female_member'] == 4
        assert su.attributes['location_problems'] == [
            'conflict', 'risk_of_eviction'
        ] 
Example #29
Source File: test_importers.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def _run_import_test(self, filename):
        importer = csv.CSVImporter(
            project=self.project, path=self.path + filename)
        config = {
            'file': self.path + filename,
            'entity_types': ['SU', 'PT'],
            'party_name_field': 'name_of_hh',
            'party_type_field': 'party_type',
            'location_type_field': 'location_type',
            'geometry_field': 'location_geometry',
            'attributes': self.attributes,
            'project': self.project,
            'allowed_tenure_types': [t[0] for t in TENURE_RELATIONSHIP_TYPES],
            'allowed_location_types': [choice[0] for choice in TYPE_CHOICES]
        }
        importer.import_data(config)

        assert Party.objects.all().count() == 10
        assert SpatialUnit.objects.all().count() == 10
        assert TenureRelationship.objects.all().count() == 10

        su1 = SpatialUnit.objects.filter(
            attributes__contains={'nid_number': '3913647224045'}).first()
        su2 = SpatialUnit.objects.filter(
            attributes__contains={'nid_number': '3913647224033'}).first()
        su3 = SpatialUnit.objects.filter(
            attributes__contains={'nid_number': '3913647225965'}).first()
        su4 = SpatialUnit.objects.filter(
            attributes__contains={'nid_number': '3913647224043'}).first()
        su5 = SpatialUnit.objects.filter(
            attributes__contains={'nid_number': '3913647224044'}).first()
        su6 = SpatialUnit.objects.filter(
            attributes__contains={'nid_number': '3913647224185'}).first()

        assert su1.geometry.geom_type == 'Point'
        assert su2.geometry.geom_type == 'LineString'
        assert su3.geometry.geom_type == 'Polygon'
        assert su4.geometry.geom_type == 'MultiPoint'
        assert su5.geometry.geom_type == 'MultiLineString'
        assert su6.geometry.geom_type == 'MultiPolygon' 
Example #30
Source File: 0002_load_initial_data.py    From Disfactory with MIT License 5 votes vote down vote up
def forward_func(apps, schema_editor):
    Factory = apps.get_model("api", "Factory")

    with open(SEED_DATA_PATH, "r") as csvfile:
        reader = csv.DictReader(csvfile)
        seed_factories = []
        for idx, datum in enumerate(reader):
            if ("test" in sys.argv) and (idx > 100):
                # reduce the amount of seed data to speed up testing
                break
            try:
                lng = float(datum["經度"])
                lat = float(datum["緯度"])
            except ValueError:
                continue
            pnt = Point(lng, lat, srid=4326)
            pnt.transform(3857)
            factory = Factory(
                lng=lng,
                lat=lat,
                point=pnt,
                landcode=datum["地號"],
                status="A",
                status_time=datetime.now(),
                name=f"full-info: row_{idx}",
            )
            seed_factories.append(factory)

    Factory.objects.bulk_create(seed_factories)