コード例 #1
0
ファイル: tests.py プロジェクト: xxqhh/django-geo-spaas
 def setUp(self):
     loc = GeographicLocation.objects.get(pk=1)
     date0 = timezone.datetime(2010,1,1, tzinfo=timezone.utc).date()
     date1 = timezone.datetime(2011,1,1, tzinfo=timezone.utc).date()
     source = Source.objects.get(pk=1)
     self.valid_form = {
             'polygon': str(Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0,
                 0)))), #loc.geometry,
             'date0': date0,
             'date1': date1,
             'source': [source.id]
         }
     self.invalid_form = {
             'polygon': 1,
             'date0': date0,
             'date1': date1,
             'source': [source.id]
         }
コード例 #2
0
def test__operational_area_permission__polygon_in_area(method):
    user = get_user()
    operational_area = OperationalArea.objects.create(
        name="Test operational area",
        location=MultiPolygon(test_polygon, srid=settings.SRID),
    )
    user.operational_areas.add(operational_area)
    request = RequestFactory().generic(method=method, path="/")
    request.user = user
    barrier_real = get_barrier_real(location=Polygon(
        ((10.0, 10.0), (10.0, 20.0), (20.0, 20.0), (20.0, 10.0), (10.0, 10.0)),
        srid=settings.SRID,
    ))

    has_permission = ObjectInsideOperationalAreaOrAnonReadOnly(
    ).has_object_permission(request, mock_view, barrier_real)

    assert has_permission
コード例 #3
0
ファイル: utils.py プロジェクト: ondrejsika2/metrocar
def parking_3():
    return Parking.objects.get_or_create(
        name="Praha - Karlovo Náměstí",
        places_count=20,
        land_registry_number="293/13",
        street="Karlovo náměstí",
        city="Praha",
        polygon=Polygon((
            (14.4166105965539693, 50.0766805985855754),
            (14.4168037156029918, 50.0763156732595718),
            (14.4169324616356764, 50.0763501002961178),
            (14.4166964272421243, 50.0770042092863648),
            (14.4164603928494692, 50.0769697827200631),
            (14.4164818505212846, 50.0766943692980107),
            (14.4164925793576391, 50.0766805985855754),
            (14.4166105965539693, 50.0766805985855754)
        ))
    )[0]
コード例 #4
0
 def test_point_in_areas(self):
     """
         Make sure we can retrieve all areas where point is
     """
     url = "/api/serviceareas/25.450234/-70.253727/get/"
     response = self.client.get(url)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertIsNotNone(response.json())
     self.assertEqual(len(response.json()), 1)
     self.assertEqual(response.json()[0]['area_name'], 'Bermuda Triangle')
     ServiceArea.objects.create(
         provider=Provider.objects.get(email='*****@*****.**'),
         price=5000000.0,
         area_name='Bermuda Triangle 2',
         area=Polygon(((-64.73, 32.31), (-80.19, 25.76), (-66.09, 18.43),
                       (-64.73, 32.31))))
     serviceareas = ServiceArea.objects.all()
     self.assertEqual(3, len(serviceareas))
コード例 #5
0
ファイル: tests.py プロジェクト: fagan2888/mapusaurus
    def test_metro(self):
        year = "2010"
        row = ('12345', 'Big City', '090', '12345', 'M1', '-45', '45',
               Polygon(((0, 0), (0, 2), (-1, 2), (0, 0))))
        field_names = ('GEOID', 'NAME', 'CSAFP', 'CBSAFP', 'LSAD', 'INTPTLAT',
                       'INTPTLON')
        command = LoadGeos()
        geo = command.process_row(year, row, field_names)

        self.assertEqual('201012345', geo['geoid'])
        self.assertEqual(Geo.METRO_TYPE, geo['geo_type'])
        self.assertEqual('Big City', geo['name'])
        self.assertEqual(None, geo['state'])
        self.assertEqual(None, geo['county'])
        self.assertEqual(None, geo['tract'])
        self.assertEqual('090', geo['csa'])
        self.assertEqual('12345', geo['cbsa'])
        self.assertEqual("2010", geo['year'])
コード例 #6
0
    def backwards(self, orm):
        regions = {}
        for region in orm.ITreeRegion.objects.all():
            multi = region.geometry
            polygons = [Polygon(*rings) for rings in multi.coords]
            regions[region.code] = polygons

            # Make sure area didn't change
            area = reduce(lambda sum, p: sum + p.area, polygons, 0)
            if area != multi.area:
                raise Exception('Area of multipolygon is incorrect')

        orm.ITreeRegion.objects.all().delete()

        for code in regions:
            for polygon in regions[code]:
                geom = MultiPolygon(polygon)
                orm.ITreeRegion(code=code, geometry=geom).save()
コード例 #7
0
 def setUpTestData(cls):
     if settings.TREKKING_TOPOLOGY_ENABLED:
         cls.path_in = PathFactory.create(
             geom=LineString((0, 0), (2, 1), srid=settings.SRID))
         cls.path_out = PathFactory.create(
             geom=LineString((5, 5), (4, 4), srid=settings.SRID))
         cls.topo_in = TopologyFactory.create(paths=[cls.path_in])
         cls.topo_out = TopologyFactory.create(paths=[cls.path_out])
     else:
         cls.topo_in = TopologyFactory.create(
             geom=LineString((0, 0), (2, 1), srid=settings.SRID))
         cls.topo_out = TopologyFactory.create(
             geom=LineString((5, 5), (4, 4), srid=settings.SRID))
     cls.intervention_in = InterventionFactory.create(target=cls.topo_in)
     cls.intervention_out = InterventionFactory.create(target=cls.topo_out)
     cls.geom_zoning = MultiPolygon(
         Polygon(((0, 0), (2, 0), (2, 2), (0, 2), (0, 0)),
                 srid=settings.SRID))
コード例 #8
0
    def test_search_service_areas_given_lat_long_pair(self):
        # NOTE: this can be improved using factoryboy.
        service_area = ServiceArea(name="Test",
                                   price="10",
                                   provider=self.provider,
                                   area=Polygon(((30.0, 10.0), (40.0, 40.0),
                                                 (20.0, 40.0), (10.0, 20.0),
                                                 (30.0, 10.0))))
        service_area.save()

        # Query strings for search via lat/long pair.
        search_url = self.service_areas + '?lat=35&long=30'
        # This point (35,30) must be contained in the previous service area created.
        response = self.client.get(search_url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.json()), 1)
        # The result should contain the service area created.
        self.assertEqual(response.json()[0]['id'], service_area.id)
コード例 #9
0
ファイル: test_models.py プロジェクト: numahell/Geotrek-admin
    def test_city_with_topo_on_loop_3(self):
        """

             +-------+
         _ _ | _ _ _ | _ _
        |    |p      |    |
        |    O-------x S  | City
        |                 |
        +-----------------+
        """
        c = City(code='005178', name='Trifouillis-les-marmottes',
                 geom=MultiPolygon(Polygon(((0, 0), (2, 0), (2, 1), (0, 1), (0, 0)),
                                           srid=settings.SRID)))
        c.save()
        p = PathFactory(geom=LineString((0.5, 0.5), (0.5, 1.5), (1.5, 1.5), (1.5, 0.5), (0.5, 0.5)))
        p.save()
        signage = SignageFactory.create(paths=[(p, 0.75, 0.75)])
        self.assertEqual(signage.city_edges.count(), 1)
コード例 #10
0
ファイル: views.py プロジェクト: kulkarniatharv/agile
def check_location(request):

    fences = {
        'I2IT':
        Polygon(((18.583211, 73.737035), (18.585046, 73.738399),
                 (18.585465, 73.737871), (18.584972, 73.737445),
                 (18.585641, 73.736537), (18.584362, 73.735507), (18.583211,
                                                                  73.737035))),
    }

    eCode = request.POST["employeeID"]

    employee_set = eDetail.objects.filter(eID__exact=eCode)

    for employee in employee_set:
        latitude = float(request.POST.get("lat", 0.0))  #18.5846382
        longitude = float(request.POST.get("lon", 0.0))  #73.7366744
        print(latitude, longitude)
        user_location = Point(latitude, longitude, srid=4326)

        branch = employee.office_branch
        print(branch)

        if (branch in fences):
            inFence = fences[branch].contains(user_location)
            print('branch found')

            if (inFence):
                today = datetime.date.today()
                now = datetime.datetime.now()
                record = AttendReport(date=today,
                                      office_branch=branch,
                                      eID=employee,
                                      attendStatus='p',
                                      time_in=now)
                print('record created!')

                if (AttendReport.objects.filter(
                        eID__exact=employee.eID).count() == 0):
                    record.save()
                    print('record saved!')
                    return render(request, 'attend_success.html')

        return render(request, 'attend_failed.html')
コード例 #11
0
    def setUp(self):
        # Make sure we're using the GB postcode functions here
        models.countries = countries
        utils.countries = countries

        self.postcode = models.Postcode.objects.create(postcode='SW1A1AA',
                                                       location=Point(
                                                           -0.141588,
                                                           51.501009))

        self.generation = models.Generation.objects.create(
            active=True,
            description="Test generation",
        )

        self.type = models.Type.objects.create(
            code="TEST_TYPE",
            description="A test area",
        )

        self.area = models.Area.objects.create(
            name="Area",
            type=self.type,
            generation_low=self.generation,
            generation_high=self.generation,
        )

        code_type = models.CodeType.objects.create(
            code='CodeType',
            description='CodeType description',
        )
        models.Code.objects.create(
            area=self.area,
            type=code_type,
            code='CODE',
        )

        polygon = Polygon(((-5, 50), (-5, 55), (1, 55), (1, 50), (-5, 50)),
                          srid=4326)
        polygon.transform(settings.MAPIT_AREA_SRID)
        self.shape = models.Geometry.objects.create(
            area=self.area,
            polygon=polygon,
        )
コード例 #12
0
ファイル: geo.py プロジェクト: tuomas777/openahjo
    def _load_mapinfo(self, ds, id_field_name, id_fixer=None):
        geom_map = {}
        lyr = ds[0]
        for idx, feat in enumerate(lyr):
            origin_id = feat[id_field_name].as_string().strip()
            if id_fixer:
                origin_id = id_fixer(origin_id)
            geom = feat.geom
            geom.srid = GK25_SRID
            geom.transform(settings.PROJECTION_SRID)
            if origin_id not in geom_map:
                plan = {'geometry': None}
                geom_map[origin_id] = plan
            else:
                plan = geom_map[origin_id]
            poly = GEOSGeometry(geom.wkb, srid=geom.srid)
            if isinstance(poly, LineString):
                try:
                    ring = LinearRing(poly.tuple)
                except Exception:
                    self.logger.error(
                        "Skipping plan %s, it's linestring doesn't close." %
                        origin_id)
                    # if the LineString doesn't form a polygon, skip it.
                    continue
                poly = Polygon(ring)
            if plan['geometry']:
                if isinstance(plan['geometry'], Polygon):
                    plan['geometry'] = MultiPolygon(plan['geometry'])
                if isinstance(poly, MultiPolygon):
                    plan['geometry'].extend(poly)
                else:
                    plan['geometry'].append(poly)
            else:
                plan['geometry'] = poly

        for key, e in geom_map.items():
            geom = e['geometry']
            if not geom.valid:
                self.logger.warning("geometry for %s not OK, fixing" % key)
                geom = geom.simplify()
                assert geom.valid
                e['geometry'] = geom
        return geom_map
 def setUp(self):
     user = User.objects.create_user(username='******',
                                     email='*****@*****.**',
                                     password='******')
     User.objects.create_user(username='******',
                              email='*****@*****.**',
                              password='******',
                              role='government_official')
     area_polygon = Polygon(area['features'][0]['geometry']['coordinates'])
     starts_at = parse_datetime(register_info['starts_at'])
     ends_at = parse_datetime(register_info['ends_at'])
     Mission.objects.create(id=1,
                            title=register_info['title'],
                            area=area_polygon,
                            description=register_info['description'],
                            starts_at=starts_at,
                            ends_at=ends_at,
                            type=register_info['type'],
                            created_by=user)
コード例 #14
0
    def test_helpers_nds(self):
        trek = TrekFactory.create(geom=LineString((2, 2), (8, 8)))
        poi = POIFactory.create(geom=Point(2.4, 2.4))
        poi2 = POIFactory.create(geom=Point(2.4, 2.4))
        service = ServiceFactory.create(geom=Point(2.8, 2.8))
        service.type.practices.add(trek.practice)
        trek.pois_excluded.add(poi2.pk)

        # /!\ District are automatically linked to paths at DB level
        d1 = DistrictFactory.create(geom=MultiPolygon(
            Polygon(((-2, -2), (3, -2), (3, 3), (-2, 3), (-2, -2)))))
        # Ensure related objects are accessible
        self.assertCountEqual(trek.pois_excluded.all(), [poi2])
        self.assertCountEqual(trek.all_pois, [poi, poi2])
        self.assertCountEqual(trek.pois, [poi])
        self.assertCountEqual(trek.services, [service])
        self.assertCountEqual(poi.treks, [trek])
        self.assertCountEqual(service.treks, [trek])
        self.assertCountEqual(trek.districts, [d1])
コード例 #15
0
ファイル: test_models.py プロジェクト: Stalfur/osmcha-django
 def setUp(self):
     self.reason_1 = SuspicionReasons.objects.create(name='possible import')
     self.reason_2 = SuspicionReasons.objects.create(name='suspect_word')
     self.changeset = Changeset.objects.create(
         id=31982803,
         uid='123123',
         user='******',
         editor='Potlatch 2',
         powerfull_editor=False,
         date=datetime.now(),
         create=2000,
         modify=10,
         delete=30,
         is_suspect=True,
         bbox=Polygon([(-71.0646843, 44.2371354), (-71.0048652, 44.2371354),
                       (-71.0048652, 44.2430624), (-71.0646843, 44.2430624),
                       (-71.0646843, 44.2371354)]))
     self.reason_1.changesets.add(self.changeset)
     self.reason_2.changesets.add(self.changeset)
コード例 #16
0
    def test_service_areas_delete(self):
        self.assertEqual(ServiceArea.objects.count(), 0)

        # NOTE: this can be improved using factoryboy.
        service_area = ServiceArea(name="Test",
                                   price="10",
                                   provider=self.provider,
                                   area=Polygon(((30.0, 10.0), (40.0, 40.0),
                                                 (20.0, 40.0), (10.0, 20.0),
                                                 (30.0, 10.0))))
        service_area.save()

        self.assertEqual(ServiceArea.objects.count(), 1)

        object_url = reverse('service-area-detail', args=[service_area.id])
        response = self.client.delete(object_url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(ServiceArea.objects.count(), 0)
コード例 #17
0
class ChangesetFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Changeset
        # create is a reserved word of DjangoModelFactory, so we need to rename
        # to be able to call it
        rename = {'form_create': 'create'}

    form_create = 20
    modify = 10
    delete = 3
    uid = '123123'
    user = '******'
    editor = 'Potlatch 2'
    powerfull_editor = False
    date = factory.LazyFunction(datetime.now)
    is_suspect = False
    bbox = Polygon([(-71.0646843, 44.2371354), (-71.0048652, 44.2371354),
                    (-71.0048652, 44.2430624), (-71.0646843, 44.2430624),
                    (-71.0646843, 44.2371354)])
コード例 #18
0
def model_defaults(feature):
    """
    Get LandUseArea defaults--useful for get_or_create()--for the feature.

    """
    try:
        polygons = [Polygon(p) for p in feature['geometry']['rings']]
        return {
            'geometry': MultiPolygon(*polygons),
            'category': feature['attributes']['C_DIG1DESC'],
            'subcategory': feature['attributes']['C_DIG2DESC'],
            'description': feature['attributes']['C_DIG3DESC'],
            'vacant_building': feature['attributes']['VACBLDG'],
            'area': round(float(feature['attributes']['SHAPE_Area']), 2),
        }
    except Exception:
        logger.exception('Exception fetching LandUseArea model defaults! '
                         'OBJECTID: %s' % feature['attributes']['OBJECTID'])
        return None
    def forwards(self, orm):
        # Adding field 'Instance.bounds'
        dummy_default_multi_polygon = MultiPolygon(
            Polygon(((0, 0), (1, 0), (1, 1), (0, 1), (0, 0))))

        db.add_column(
            u'treemap_instance',
            'bounds',
            self.gf('django.contrib.gis.db.models.fields.MultiPolygonField')(
                srid=3857, default=dummy_default_multi_polygon),
            keep_default=False)

        for instance in orm.Instance.objects.all():
            point = instance.center
            calculated_box = MultiPolygon(
                Polygon.from_bbox((point.x - 2500, point.y - 2500,
                                   point.x + 2500, point.y + 2500)))
            instance.bounds = calculated_box
            instance.save()
コード例 #20
0
        def test_serialization(self):
            """
            Regular JSON serialization should output float values
            """
            from django.contrib.gis.geos import Polygon
            now = datetime.datetime.now()
            polygon = Polygon([[51.778564453125, 35.59925232772949],
                               [50.1470947265625, 34.80929324176267],
                               [52.6080322265625, 34.492975402501536],
                               [51.778564453125, 35.59925232772949]])

            saved_polygon = SavePolygon(polygon=polygon, created=now)
            serializer = PolygonSerializer(saved_polygon)

            self.assertEqual(serializer.data['polygon'],
                             [[51.778564453125, 35.59925232772949],
                              [50.1470947265625, 34.80929324176267],
                              [52.6080322265625, 34.492975402501536],
                              [51.778564453125, 35.59925232772949]])
コード例 #21
0
    def test_02_area_feature_string_representation(self):
        """

        """
        test_data = self.test_data.copy()
        _area_data = json.loads(
            open(os.path.join(HERE, 'test.data/models.test.area-feature.json'),
                 'r').read())
        _area_data.update(dict(polygon=Polygon(_area_data.get('polygon'))))
        test_data.update(
            dict(
                policy=Policy(**self.test_data['policy']),
                geometry_collection=GeometryCollection(
                    **self.test_data['geometry_collection']),
                **_area_data,
            ))
        my_new_pf = AreaFeature(**test_data)
        self.assertEqual(str(my_new_pf),
                         '%s:%s' % (my_new_pf.identifier, my_new_pf.name))
コード例 #22
0
    def test_nearest_to_point_returns_nearest_country(self):
        country1 = CountryFactory.build()
        country1.save()

        country2 = CountryFactory.build()
        country2.geometry = MultiPolygon([
            Polygon([
                Point(1000, 1000),
                Point(1000, 1001),
                Point(1001, 1000),
                Point(1001, 1001),
                Point(1000, 1000),
            ]),
        ])
        country2.save()

        point = Point(0, 0)
        nearest_country = Country.objects.nearest_to_point(point)
        self.assertEqual(nearest_country, country1)
コード例 #23
0
def get_geojson(request):
    """View used by the map javascript to fetch geojson data for each map tile.

    This view receives some parameters via GET request and returns a geojson
    reponse.

    Params:
        bounds: string of the form "lat_lo,lng_lo,lat_hi,lng_hi", where "lo"
            corresponds to the southwest corner of the bounding box,
            while "hi" corresponds to the northeast corner of that box.
        zoom: the map zoom level.
        models: a list of model to filter, separated by comma, of the form
            "app_name.ModelNamel".
        project - the id of the the project with which the filtered objects
            should have ralations. (Optional)

    """
    bounds = request.GET.get('bounds', None)
    zoom = int(request.GET.get('zoom', 13))
    models = request.GET.get('models', '')
    project = request.GET.get('project', None)

    if not bounds and not project:
        return HttpResponseBadRequest(to_json({'error': 'Invalid query'}),
                                      mimetype="application/x-javascript")

    if bounds:
        x1, y2, x2, y1 = [float(i) for i in bounds.split(',')]
        polygon = Polygon(((x1, y1), (x1, y2), (x2, y2), (x2, y1), (x1, y1)))

        intersects_polygon = (Q(points__intersects=polygon)
                              | Q(lines__intersects=polygon)
                              | Q(polys__intersects=polygon))
    else:
        intersects_polygon = Q()

    models = [cache.get_model(*m.split('.')) for m in models.split(',') if m]
    d = _fetch_geo_objects(intersects_polygon, zoom, models, project)
    l = []
    for objs in d.values():
        l.extend(objs)
    geojson = create_geojson(l)
    return HttpResponse(to_json(geojson), mimetype="application/x-javascript")
コード例 #24
0
ファイル: layer.py プロジェクト: majo72/mrmap
    def _create_metadata_record(self, parent_service: Service,
                                group: MrMapGroup):
        """ Creates a Metadata record from the OGCLayer object

        Args:
            self (OGCLayer): The OGCLayer object (result of parsing)
            parent_service (Service): The parent Service object 
            group (MrMapGroup): The creator/owner group
        Returns:
             metadata (Metadata): The persisted metadata object
        """
        metadata = Metadata()
        md_type = MetadataEnum.LAYER.value
        metadata.metadata_type = md_type
        metadata.title = self.title
        metadata.abstract = self.abstract
        metadata.online_resource = parent_service.metadata.online_resource
        metadata.capabilities_original_uri = parent_service.metadata.capabilities_original_uri
        metadata.identifier = self.identifier
        metadata.contact = parent_service.metadata.contact
        metadata.access_constraints = parent_service.metadata.access_constraints
        metadata.is_active = False
        metadata.created_by = group

        # Save metadata to use id afterwards
        metadata.save()

        # create bounding box polygon
        bounding_points = ((float(self.capability_bbox_lat_lon["minx"]),
                            float(self.capability_bbox_lat_lon["miny"])),
                           (float(self.capability_bbox_lat_lon["minx"]),
                            float(self.capability_bbox_lat_lon["maxy"])),
                           (float(self.capability_bbox_lat_lon["maxx"]),
                            float(self.capability_bbox_lat_lon["maxy"])),
                           (float(self.capability_bbox_lat_lon["maxx"]),
                            float(self.capability_bbox_lat_lon["miny"])),
                           (float(self.capability_bbox_lat_lon["minx"]),
                            float(self.capability_bbox_lat_lon["miny"])))
        metadata.bounding_geometry = Polygon(bounding_points)

        metadata.save()

        return metadata
コード例 #25
0
def unwrap_polygon(polygon):
    """
    Given a polygon, returns a corresponding polygon that 'unwraps' the coordinate such, if the
    coordinates cross the anti-meridian, the longitudes are changed to be only positive or negative.

    This fixes weird issues that may occur at the anti-meridian,
    so that a polygon is now represented as (160 45), (200 45), (200, 55), (160, 55), (160 45)
    instead of (160 45), (-160 45), (-160, 55), (160, 55), (160 45)

    This function assumes that we always want to wrap the polygon around the world the shortest
    possible way, defaulting to wrapping around the prime meridian if the polygon wraps around
    exactly half of the globe
    """
    # Get all the longitudes from the passed-in coordinates
    longitudes = [c[0] for c in polygon.coords[0]]
    # If the sum total of the minimum and maximum longitudes is greater than 180, we're wrapping
    # around the anti-meridian; otherwise, we can just leave the polygon alone (if it happens to be
    # *exactly* halfway around the globe, we default to wrapping around the *prime* meridian)
    if (abs(min(longitudes)) + abs(max(longitudes))) <= 180:
        return polygon

    # We have to figure out if the resulting longitude should be positive or negative; we decide
    # that based on which side of the polygon is "larger" (has the smallest longitude) after
    # splitting it on the anti-meridian
    smallest_longitude = min(longitudes, key=lambda value: abs(value))

    # Use that point to determine what sign we use for longitudes
    is_negative_lng = True if smallest_longitude < 0 else False
    unwrapped_coords = []

    for point in polygon.coords[0]:
        lng = point[0]
        lat = point[1]

        if is_negative_lng and lng > 0:
            unwrapped_coords.append((lng - 360, lat))
        elif not is_negative_lng and lng < 0:
            unwrapped_coords.append((lng + 360, lat))
        else:
            unwrapped_coords.append(point)

    return Polygon(unwrapped_coords)
コード例 #26
0
ファイル: tests.py プロジェクト: gaberosser/crime-fighter
    def setUp(self):
        # met regions
        dt = models.DivisionType(name='met_region')
        dt.save()

        def pre_save_callback(sender, instance, *args, **kwargs):
            instance.type = dt

        mapping = {
            'name': 'NAME',
            'mpoly': 'MULTIPOLYGON',
        }

        lm = LayerMapping(models.Division, METREGIONS, mapping, transform=False)
        pre_save.connect(pre_save_callback, sender=models.Division)
        try:
            lm.save(strict=True, verbose=False)
        except Exception as exc:
            print repr(exc)
            raise
        finally:
            pre_save.disconnect(pre_save_callback, sender=models.Division)

        # toy regions
        dt = models.DivisionType(name='toy')
        dt.save()

        coords = [
            [(1, 1), (2, 1), (2, 2), (1, 2), (1, 1)],
            [(2, 1), (3, 1), (3, 2), (2, 2), (2, 1)],
            [(3, 1), (4, 1), (4, 2), (3, 2), (3, 1)],
            [(1, 2), (2, 2), (2, 3), (1, 3), (1, 2)],
            [(2, 2), (3, 2), (3, 3), (2, 3), (2, 2)],
            [(3, 2), (4, 2), (4, 3), (3, 3), (3, 2)],
            [(1, 3), (2, 3), (2, 4), (1, 4), (1, 3)],
            [(2, 3), (3, 3), (3, 4), (2, 4), (2, 3)],
            [(3, 3), (4, 3), (4, 4), (3, 4), (3, 3)],
            [(4, 3), (5, 3), (5, 4), (4, 4), (4, 3)],
        ]
        for (i, c) in enumerate(coords):
            mpoly = MultiPolygon(Polygon(c))
            models.Division(name="%02u" % (i+1), code=str(i), mpoly=mpoly, type=dt).save()
コード例 #27
0
def osm_get_multipolygon_for_rel_id(id, level=8):
    url = 'http://overpass-api.de/api/interpreter'
    query = '[out:json];rel(' + str(id) + ');out geom;'
    payload = {'data': query}
    r = requests.post(url, payload)
    info = []
    if r.status_code == 200:
        r.encoding = 'utf-8'
        try:
            recup = json.loads(r.text)
            if 'elements' in recup.keys():
                elements = recup.get('elements')
                for el in elements:
                    if 'tags' in el.keys():
                        tags = el.get('tags')
                        if 'admin_level' in tags:
                            if tags.get('admin_level') == str(level):
                                info.append(str(tags.get('name')))
                                if 'members' in el.keys():
                                    members = el.get('members')
                                    ways = []
                                    for m in members:
                                        if 'geometry' in m.keys() and m.get(
                                                "type") == "way":
                                            ways.append(m.get('geometry'))
                                    points = order_ways(ways)
                                    points.append(points[0])
                                    line = LinearRing(points)
                                    info.append(Polygon(line))
                                    return info

            print("Town found but can't make the boundary")
            return False
        except Exception as e:
            print(
                'osm_get_multipolygon_for_rel_id(id) : Decoding JSON has failed'
            )
            print(str(e))
    else:
        print("No data found id")

    return False
コード例 #28
0
ファイル: populate.py プロジェクト: gaberosser/crime-fighter
def setup_monsuru_cad_grid(verbose=False):
    DATADIR = os.path.join(settings.DATA_DIR, 'monsuru/cad_grids')
    fin = os.path.join(DATADIR, 'grids')
    s = shapefile.Reader(fin)
    dt = models.DivisionType.objects.get(name='monsuru_250m_grid')

    count = 0

    for x in s.shapeRecords():
        poly = Polygon([tuple(t) for t in x.shape.points])
        div = models.Division(
            type=dt,
            name=str(x.record[5]),
            mpoly=MultiPolygon(poly),
        )
        div.save()
        count += 1

    if verbose:
        print "Saved %d grid records" % count
コード例 #29
0
ファイル: tests.py プロジェクト: PresidentNick/paleocore
 def test_occurrence_create_simple(self):
     """
     Test Occurrence instance creation with the simplest possible attributes, coordinates only
     """
     starting_record_count = Occurrence.objects.count()  # get current number of occurrence records
     # The simplest occurrence instance we can create needs only a location.
     # Using the instance creation and then save methods
     poly = Polygon(
         ((677158.6189000001, 1227037.2491999995), (677158.4829000002, 1228987.2874999996),
          (677218.1513999999, 1226987.2874999996), (677218.1513999999, 1226920.9891999997),
          (677158.6189000001, 1227037.2491999995))
     )
     locality_3 = Locality.objects.create(paleolocalitynumber=3, geom=poly)
     new_occurrence = Occurrence.objects.create(geom=Point(658198.7081000003963709, 1221366.8992999996989965),
                                                locality=locality_3)
     now = datetime.now()
     self.assertEqual(Occurrence.objects.count(), starting_record_count+1)  # test that one record has been added
     self.assertEqual(new_occurrence.catalognumber, "--")  # test catalog number generation in save method
     self.assertEqual(new_occurrence.datelastmodified.day, now.day)  # test date last modified is correct
     self.assertEqual(new_occurrence.point_X(), 658198.7081000003963709)
コード例 #30
0
    def __init__(self, commit=False):
        """Populate the self.grid list. Defaults to no database change. """

        self.grid = self.generate_grid()

        if commit:
            for tile in self.grid:
                r = models.Topo50grid(
                    identifier=tile[0],
                    nzms_ymax=tile[1]['north'],
                    nzms_xmax=tile[1]['east'],
                    nzms_ymin=tile[1]['south'],
                    nzms_xmin=tile[1]['west'],
                    geom=Polygon(tile[1]['coords']),
                )
                # Test for touching an island.
                island = models.Topo50_Island.objects.filter(
                    geom__intersects=r.geom)
                if island.count():
                    r.save()