def test_transform_multipolygon(self): geometry = Geometry( OGRGeometry('MULTIPOLYGON (((0 0,0 5,5 5,0 0)))')).transform( SpatialReference(26917)) self.assertIsInstance(geometry, Geometry) self.assertEqual(geometry.geometry.geom_name, 'MULTIPOLYGON') assertRegex( self, geometry.wkt, r'MULTIPOLYGON \(\(\(-85.488743884\d{6} 0.0,-85.488743884\d{6} 0.000045096\d{6},-85.488699089\d{6} 0.000045096\d{6},-85.488743884\d{6} 0.0\)\)\)' )
def test13_attr_value(self): "Testing the attr_value() method." s1 = SpatialReference('WGS84') self.assertRaises(TypeError, s1.__getitem__, 0) self.assertRaises(TypeError, s1.__getitem__, ('GEOGCS', 'foo')) self.assertEqual('WGS 84', s1['GEOGCS']) self.assertEqual('WGS_1984', s1['DATUM']) self.assertEqual('EPSG', s1['AUTHORITY']) self.assertEqual(4326, int(s1['AUTHORITY', 1])) self.assertEqual(None, s1['FOOBAR'])
def convertGeojsonFeatureToGEOS(self, feature): geos_geometries = [] if "properties" in feature and "srid" in feature["properties"]: srid = feature["properties"]["srid"] else: srid = 4326 if feature["geometry"]["type"] == "MultiPolygon": for polygon in feature["geometry"]["coordinates"]: geom = {"type": "Polygon", "coordinates": [polygon[0]]} geos = GEOSGeometry(json.dumps(geom), srid=srid) if geos.srid != self.db_srid: ct = CoordTransform(SpatialReference(geos.srid), SpatialReference(self.db_srid)) geos.transform(ct) geos_geometries.append(geos) else: try: geos = GEOSGeometry(json.dumps(feature["geometry"]), srid=srid) except: raise TypeError( "Invalid GEOJSON geometry for cluster area. Use Polygon or Multipolygon" ) if geos: if geos.srid != self.db_srid: ct = CoordTransform(SpatialReference(geos.srid), SpatialReference(self.db_srid)) geos.transform(ct) geos_geometries.append(geos) return geos_geometries
def test02_bad_wkt(self): "Testing initialization on invalid WKT." for bad in bad_srlist: try: srs = SpatialReference(bad) srs.validate() except (SRSException, GDALException): pass else: self.fail('Should not have initialized on bad WKT "%s"!')
def load_boundary_set(self, slug, definition, data_sources, options): BoundarySet.objects.filter( slug=slug).delete() # also deletes boundaries boundary_set = BoundarySet.objects.create( slug=slug, last_updated=definition['last_updated'], name=definition['name'], singular=definition['singular'], domain=definition['domain'], authority=definition['authority'], source_url=definition['source_url'], licence_url=definition['licence_url'], start_date=definition['start_date'], end_date=definition['end_date'], notes=definition['notes'], extra=definition['extra'], ) boundary_set.extent = [None, None, None, None] # [xmin, ymin, xmax, ymax] for data_source in data_sources: log.info( _('Loading %(slug)s from %(source)s') % { 'slug': slug, 'source': data_source.name }) layer = data_source[0] layer.source = data_source # to trace the layer back to its source if definition.get('srid'): srs = SpatialReference(definition['srid']) else: srs = layer.srs for feature in layer: feature = Feature(feature, definition, srs, boundary_set) feature.layer = layer # to trace the feature back to its source if feature.is_valid(): log.info(_('%(slug)s...') % {'slug': feature.slug}) boundary = self.load_boundary(feature, options['merge']) boundary_set.extend(boundary.extent) if None not in boundary_set.extent: # unless there are no features boundary_set.save() log.info( _('%(slug)s count: %(count)i') % { 'slug': slug, 'count': Boundary.objects.filter(set=boundary_set).count() })
def add_aois_to_shapefile(self, ds, job_object): aois = job_object.aois.all() if len(aois) == 0: return geo_field = aois[0].polygon # Get the right geometry type number for ogr ogr_type = OGRGeomType(geo_field.geom_type).num # Set up the native spatial reference of the geometry field using the srid native_srs = SpatialReference(geo_field.srid) # create the AOI layer layer = lgdal.OGR_DS_CreateLayer(ds, 'Workcells', native_srs._ptr, ogr_type, None) # Create the fields that each feature will have fields = AOI._meta.fields attributes = [] for field in fields: if field.name in 'id, active, name, created_at, updated_at, analyst, priority, status, properties': attributes.append(field) for field in attributes: data_type = 4 if field.name == 'id': data_type = 0 fld = lgdal.OGR_Fld_Create(str(field.name), data_type) added = lgdal.OGR_L_CreateField(layer, fld, 0) check_err(added) # Getting the Layer feature definition. feature_def = lgdal.OGR_L_GetLayerDefn(layer) # Loop through queryset creating features for item in aois: feat = lgdal.OGR_F_Create(feature_def) for idx, field in enumerate(attributes): if field.name == 'properties': value = json.dumps(item.properties) else: value = getattr(item, field.name) string_value = str(value)[:80] lgdal.OGR_F_SetFieldString(feat, idx, string_value) # Transforming & setting the geometry geom = item.polygon ogr_geom = OGRGeometry(geom.wkt, native_srs) check_err(lgdal.OGR_F_SetGeometry(feat, ogr_geom._ptr)) # create the feature in the layer. check_err(lgdal.OGR_L_CreateFeature(layer, feat)) check_err(lgdal.OGR_L_SyncToDisk(layer))
def build_bbox_filter(srid, bbox_val, field_name): poly = poly_from_bbox(bbox_val) srs = srid_to_srs(srid) poly.set_srid(srs.srid) if srid != settings.PROJECTION_SRID: source_srs = SpatialReference(settings.PROJECTION_SRID) ct = CoordTransform(srs, source_srs) poly.transform(ct) return {"%s__within" % field_name: poly}
def add_features_subset_to_shapefile(self, ds, features, layer_name): if len(features) == 0: return geo_field = features[0].the_geom # Get the right geometry type number for ogr ogr_type = OGRGeomType(geo_field.geom_type).num # Set up the native spatial reference of the geometry field using the srid native_srs = SpatialReference(geo_field.srid) # create the Feature layer layer = lgdal.OGR_DS_CreateLayer(ds, layer_name, native_srs._ptr, ogr_type, None) # Create the fields that each feature will have fields = Feature._meta.fields attributes = [] for field in fields: if field.name in 'id, analyst, template, created_at, updated_at, job, project': attributes.append(field) for field in attributes: data_type = 4 if field.name == 'id': data_type = 0 fld = lgdal.OGR_Fld_Create(str(field.name), data_type) added = lgdal.OGR_L_CreateField(layer, fld, 0) check_err(added) # Getting the Layer feature definition. feature_def = lgdal.OGR_L_GetLayerDefn(layer) # Loop through queryset creating features for item in features: feat = lgdal.OGR_F_Create(feature_def) for idx, field in enumerate(attributes): value = getattr(item, field.name) # if field.name == 'template': # value = value.name string_value = str(value) lgdal.OGR_F_SetFieldString(feat, idx, string_value) # Transforming & setting the geometry geom = item.the_geom ogr_geom = OGRGeometry(geom.wkt, native_srs) check_err(lgdal.OGR_F_SetGeometry(feat, ogr_geom._ptr)) # create the feature in the layer. check_err(lgdal.OGR_L_CreateFeature(layer, feat)) check_err(lgdal.OGR_L_SyncToDisk(layer))
def add_postgis_srs(srs, auth_name='EPSG', auth_srid=None, ref_sys_name=None): """ This function takes a GDAL SpatialReference system and adds its information to the PostGIS `spatial_ref_sys` table -- enabling spatial transformations with PostGIS. This is handy for adding spatial reference systems not included by default with PostGIS. For example, the following adds the so-called "Google Maps Mercator Projection" (available in GDAL 1.5): >>> add_postgis_srs(SpatialReference(900913)) Keyword Arguments: auth_name: This keyword may be customized with the value of the `auth_name` field. Defaults to 'EPSG'. auth_srid: This keyword may be customized with the value of the `auth_srid` field. Defaults to the SRID determined by GDAL. ref_sys_name: For SpatiaLite users only, sets the value of the the `ref_sys_name` field. Defaults to the name determined by GDAL. """ from django.contrib.gis.db.backend import SpatialBackend from django.contrib.gis.models import SpatialRefSys from django.contrib.gis.gdal import SpatialReference if SpatialBackend.oracle or SpatialBackend.mysql: raise Exception( 'This utility not supported on Oracle or MySQL spatial backends.') if not isinstance(srs, SpatialReference): srs = SpatialReference(srs) if srs.srid is None: raise Exception( 'Spatial reference requires an SRID to be compatible with PostGIS.' ) # Initializing the keyword arguments dictionary for both PostGIS and SpatiaLite. kwargs = { 'srid': srs.srid, 'auth_name': auth_name, 'auth_srid': auth_srid or srs.srid, 'proj4text': srs.proj4, } # Backend-specific keyword settings. if SpatialBackend.postgis: kwargs['srtext'] = srs.wkt if SpatialBackend.spatialite: kwargs['ref_sys_name'] = ref_sys_name or srs.name # Creating the spatial_ref_sys model. sr, created = SpatialRefSys.objects.get_or_create(**kwargs)
def get_units(cls, wkt): """ Class method used by GeometryField on initialization to retrive the units on the given WKT, without having to use any of the database fields. """ if HAS_GDAL: return SpatialReference(wkt).units else: m = cls.units_regex.match(wkt) return m.group('unit'), m.group('unit_name')
def parse_lat_lon(query_params): lat = query_params.get('lat', None) lon = query_params.get('lon', None) if not lat and not lon: return None if not lat or not lon: raise ParseError("you must supply both 'lat' and 'lon'") try: lat = float(lat) lon = float(lon) except ValueError: raise ParseError("'lat' and 'lon' must be floating point numbers") point = Point(lon, lat, srid=DEFAULT_SRID) if DEFAULT_SRID != DATABASE_SRID: ct = CoordTransform(SpatialReference(DEFAULT_SRID), SpatialReference(DATABASE_SRID)) point.transform(ct) return point
def get_extent_from_text(points, srid_in, srid_out): """Transform an extent from srid_in to srid_out.""" proj_in = SpatialReference(srid_in) proj_out = SpatialReference(srid_out) if srid_out == 900913: if int(float(points[0])) == -180: points[0] = -179 if int(float(points[1])) == -90: points[1] = -89 if int(float(points[2])) == 180: points[2] = 179 if int(float(points[3])) == 90: points[3] = 89 wkt = 'POINT(%f %f)' % (float(points[0]), float(points[1])) wkt2 = 'POINT(%f %f)' % (float(points[2]), float(points[3])) ogr = OGRGeometry(wkt) ogr2 = OGRGeometry(wkt2) if hasattr(ogr, 'srs'): ogr.srs = proj_in ogr2.srs = proj_in else: ogr.set_srs(proj_in) ogr2.set_srs(proj_in) ogr.transform_to(proj_out) ogr2.transform_to(proj_out) wkt = ogr.wkt wkt2 = ogr2.wkt mins = wkt.replace('POINT (', '').replace(')', '').split(' ') maxs = wkt2.replace('POINT (', '').replace(')', '').split(' ') mins.append(maxs[0]) mins.append(maxs[1]) return mins
def convertGeojsonFeatureToGEOS(self, feature): geos_geometries = [] if "properties" in feature and "srid" in feature["properties"]: srid = feature["properties"]["srid"] else: srid = 4326 if feature["geometry"]["type"] == "MultiPolygon": for polygon in feature["geometry"]["coordinates"][0]: geom = {"type": "Polygon", "coordinates": [polygon]} geos = GEOSGeometry(json.dumps(geom), srid=srid) if geos.srid != self.srid_db: ct = CoordTransform(SpatialReference(geos.srid), SpatialReference(self.srid_db)) geos.transform(ct) geos_geometries.append(geos) else: try: geos = GEOSGeometry(json.dumps(feature["geometry"]), srid=srid) except: return None if geos: if geos.srid != self.srid_db: ct = CoordTransform(SpatialReference(geos.srid), SpatialReference(self.srid_db)) geos.transform(ct) geos_geometries.append(geos) return geos_geometries
def reimport(self): """ Connects to the Oregon facility JSON endpoint and reimports all the facilities """ response = requests.get("https://data.oregon.gov/resource/spxe-q5vj.json") js = response.json() # the data source uses WGS84 coords, so we have to transform them gcoord = SpatialReference(4326) mycoord = SpatialReference(3644) trans = CoordTransform(gcoord, mycoord) with transaction.atomic(): # wipe out the existing facilties Facility.objects.all().delete() for row in js: try: p = Point(float(row['location']['longitude']), float(row['location']['latitude']), srid=4326) except KeyError: continue p.transform(trans) f = Facility( name=row['boating_facility_name'], managed_by=row.get('managed_by', ''), telephone=row.get('telephone', {}).get('phone_number', ''), ramp_type=row.get('ramp_type_lanes', ''), trailer_parking=row.get('trailer_parking', ''), moorage=row.get('moorage', ''), launch_fee=row.get('launch_fee', ''), restroom=row.get('restroom', ''), supplies=row.get('supplies', ''), gas_on_water=row.get('gas_on_the_water', ''), diesel_on_water=row.get('diesel_on_the_water', ''), waterbody=row.get('waterbody', ''), fish_cleaning=row.get('fish_cleaning_station', ''), pumpout=row.get('pumpout', ''), dump_station=row.get('dump_station', ''), the_geom=p, icon_url=row.get('boater_services', ''), ) f.save()
def Mapa_Estado(request, id_estado): obj = Uf.objects.filter(id=id_estado) ct = CoordTransform(SpatialReference('EPSG:4326'), SpatialReference('EPSG:900913')) nome = '' for feat in obj: nome = feat.get_name() dados = [] for p in obj: aux = p.mpoly aux.transform(ct) dados.append(aux) return render_to_response( 'mapa.html', RequestContext(request, { 'dados': dados, 'nome': nome }))
def srid_to_srs(srid): if not srid: srid = DEFAULT_SRID try: srid = int(srid) except ValueError: raise ParseError("'srid' must be an integer") try: srs = SpatialReference(srid) except SRSException: raise ParseError("SRID %d not found (try 4326 for GPS coordinate system)" % srid) return srs
def run(self): site_file = os.path.join(self.INPUT_ROOT, self.site) with open(site_file, 'r') as f: poly_wkt = f.read() poly = GEOSGeometry(poly_wkt) # convert from lat-long to utm (xy) wgsProj = SpatialReference('+proj=longlat +datum=WGS84') utmProj = SpatialReference('+proj=utm +zone=18 +ellps=WGS84') ct = CoordTransform(wgsProj, utmProj) poly.transform(ct) # pass the polygon in form of lines in a numpy array xy = np.asarray(poly.tuple[0]) sps = placeSensor(xy, rng=self.sensor_rng, fov=self.sensor_fov, skip_small=True) ct = CoordTransform(utmProj, wgsProj) sps.transform(ct) with self.output().open('w') as f: f.write(sps.wkt)
def run(verbose=True): df = pd.read_csv(csv_file, converters=StringConverter()) mapping = { row["original"]: row["new"] for idx, row in pd.read_csv(column_mapping).iterrows() } df = df.rename(columns=mapping) l = list(set(mapping.values())) df = df[l] print(df.head(n=5)) category = Category.objects.filter(text="小型工程").first() DistrictMinorWorkMetaData.objects.all().delete() for idx, row in df.iterrows(): row["document_date"] = datetime.strptime(row["document_date"], "%d/%m/%Y") try: row["expected_start_date"] = datetime.strptime( row["expected_start_date"], "%d/%m/%Y") except: row["expected_start_date"] = None try: row["expected_end_date"] = datetime.strptime( row["expected_end_date"], "%d/%m/%Y") except: row["expected_end_date"] = None audience = [] audience_labels = ["區內所有居民", "老人", "青少年", "傷殘人士", "兒童及家長"] for x, word in zip( ["all_citizen", "elderly", "youth", "disabled", "kids"], audience_labels): if row["audience_" + x].lower() == "yes": audience.append(word) row["audience"] = ",".join(audience) row["ballpark_text"] = row["ballpark"] try: row["ballpark"] = float(row["ballpark_text"].replace(",", "")) except: row["ballpark"] = 0 m = DistrictMinorWorkMetaData(**row) m.category = category m.save() sr = SpatialReference('EPSG:2326') DistrictMinorWork.objects.all().delete() lm = LayerMapping(DistrictMinorWork, world_shp, dmw_mapping, transform=True) lm.save(strict=True, verbose=verbose) for dmw in DistrictMinorWork.objects.all(): dmw.metadata = DistrictMinorWorkMetaData.objects.get( identifier=dmw.identifier) dmw.save()
def test13_attr_value(self): "Testing the attr_value() method." s1 = SpatialReference("WGS84") with self.assertRaises(TypeError): s1.__getitem__(0) with self.assertRaises(TypeError): s1.__getitem__(("GEOGCS", "foo")) self.assertEqual("WGS 84", s1["GEOGCS"]) self.assertEqual("WGS_1984", s1["DATUM"]) self.assertEqual("EPSG", s1["AUTHORITY"]) self.assertEqual(4326, int(s1["AUTHORITY", 1])) self.assertIsNone(s1["FOOBAR"])
def save_mask(): try: ct=CoordTransform(SpatialReference('WGS84'), SpatialReference('4527')) label_path=os.path.join(uploadfiles[0],'labelRPC.tif') dataset = gdal.Open(label_path) GeoTransform = dataset.GetGeoTransform() if dataset == None: return im_width = dataset.RasterXSize # 栅格矩阵的列数 im_height = dataset.RasterYSize # 栅格矩阵的行数 cood_trans=lambda L,C:(GeoTransform[0] + C * GeoTransform[1] + L * GeoTransform[2],GeoTransform[3] + C * GeoTransform[4] + L * GeoTransform[5]) map_polygon=Polygon(LinearRing(cood_trans(0,0),cood_trans(0,im_width),cood_trans(im_height,im_width),cood_trans(im_height,0),cood_trans(0,0))) Bmap.objects.filter(id=id).update(polygon=map_polygon) im_data = dataset.ReadAsArray(0, 0, im_width, im_height) # 获取数据 dataset = None types = np.unique(im_data) for label_type in types: # if label_type in (0,): # continue mp = fit_by_contours((im_data == label_type).astype(np.uint8), GeoTransform) m = Mask(map=Bmap.objects.get(id=id),type_id=int(label_type), mask=mp,area=round(mp.transform(ct,clone=True).area/1000000,2)) m.save() # img[im_data == label_type]=127 # cv2.imwrite(str(label_type)+".jpg",img) if label_type!=0: payload = "<featureType><name>" + str(id) + '_' + str(m.type_id) + "</name><nativeName>myweb_mask</nativeName>"" \ ""<cqlFilter>type_id=" + str(m.type_id) + " and map_id=" + str(id) + "</cqlFilter></featureType>" headers = {'Content-type': 'text/xml'} resp = requests.post(mask_url, auth=('admin', 'geoserver'), data=payload, headers=headers) if resp.status_code != 201: raise Exception('Upload to geoserver error') else: cat = Catalog(map_url, 'admin', 'geoserver') layer = cat.get_layer('Mask:'+str(id)+'_'+str(m.type_id)) layer.default_style=cat.get_style(str(label_type), 'Mask') cat.save(layer) cat.reload() return "上传成功" except Exception as e: return Exception("上传失败,拟合图斑出错:"+str(e))
def test11_wellknown(self): "Testing Well Known Names of Spatial References." for s in well_known: srs = SpatialReference(s.wk) self.assertEqual(s.name, srs.name) for tup in s.attrs: if len(tup) == 2: key = tup[0] exp = tup[1] elif len(tup) == 3: key = tup[:2] exp = tup[2] self.assertEqual(srs[key], exp)
def fix_extent(apps, schema_editor): try: Project = apps.get_model("gvsigol_core", "Project") from django.contrib.gis import gdal major_version = gdal.gdal_version().split(".")[0] if int(major_version) >= 3: # fix effect of previous migration on GDAL 3 installations try: # newer Django versions include AxisOrder settings to manage this issue from django.contrib.gis.gdal import AxisOrder # @UnresolvedImport is expected in Diago < 3.1 # newer Django versions include AxisOrder settings to manage this issue # if AxisOrder class exists, the transformation on 0029_fill_project_extent4326 # should be successful, because AxisOrder.TRADITIONAL is the default behaviour return except: pass from django.contrib.gis.gdal import SpatialReference, CoordTransform from django.contrib.gis.geos import Point crs4326 = SpatialReference("EPSG:4326") crs3857 = SpatialReference("EPSG:3857") transform = CoordTransform(crs3857, crs4326) for project in Project.objects.all(): extent3857_minx, extent3857_miny, extent3857_maxx, extent3857_maxy = [ float(f) for f in project.extent.split(',') ] point = Point(extent3857_minx, extent3857_miny, srid=3857) point.transform(transform) project.extent4326_miny, project.extent4326_minx = point.coords point = Point(extent3857_maxx, extent3857_maxy, srid=3857) point.transform(transform) project.extent4326_maxy, project.extent4326_maxx = point.coords project.save() except Exception as error: import logging logger = logging.getLogger() logger.exception("error") print str(error)
def photo_info(request): form = DelfiPhotoInfoRequestForm(request.query_params) if form.is_valid(): photo = form.cleaned_data['id'] our_ref = SpatialReference(4326) delfi_ref = SpatialReference(3301) trans = CoordTransform(our_ref, delfi_ref) location = Point(x=photo.lon, y=photo.lat, srid=4326) location.transform(trans) source_str = '' if photo.source and photo.source_key: source_str = photo.source.description + ' ' + photo.source_key return Response({ 'id': photo.id, 'author': photo.author, 'description': photo.description, 'latitude': location.y, 'longitude': location.x, 'source': source_str, 'url': request.build_absolute_uri( reverse('project.ajapaik.views.photoslug', args=(photo.id, photo.get_pseudo_slug()))), 'thumbUrl': request.build_absolute_uri( reverse('project.ajapaik.views.image_thumb', args=(photo.id, 400, photo.get_pseudo_slug()))) }) return Response({})
def test09b_srs_transform(self): "Testing transform()." orig = OGRGeometry('POINT (-104.609 38.255)', 4326) trans = OGRGeometry('POINT (992385.4472045 481455.4944650)', 2774) # Using an srid, a SpatialReference object, and a CoordTransform object # or transformations. t1, t2, t3 = orig.clone(), orig.clone(), orig.clone() t1.transform(trans.srid) t2.transform(SpatialReference('EPSG:2774')) ct = CoordTransform(SpatialReference('WGS84'), SpatialReference(2774)) t3.transform(ct) # Testing use of the `clone` keyword. k1 = orig.clone() k2 = k1.transform(trans.srid, clone=True) self.assertEqual(k1, orig) self.assertNotEqual(k1, k2) prec = 3 for p in (t1, t2, t3, k2): self.assertAlmostEqual(trans.x, p.x, prec) self.assertAlmostEqual(trans.y, p.y, prec)
def __init__(self, feature, definition, srs=None, boundary_set=None, start_date=None, end_date=None): srs = srs or SpatialReference(4326) self.feature = feature self.definition = definition self.geometry = Geometry(feature.geom).transform(srs) self.boundary_set = boundary_set self.start_date = start_date self.end_date = end_date
def _create_layer(self, tmp_name, fieldmapping, geofield, output_srid, encodign="utf-8", layer_name=""): driver = ogr.GetDriverByName(self.driver_name) datasource = lgdal.OGR_Dr_CreateDataSource(driver._ptr, tmp_name, None) if datasource is None: raise Exception("Could not create shapefile.") if hasattr(geofield, 'srid'): native_srs = SpatialReference(geofield.srid) else: native_srs = SpatialReference(geofield._srid) if output_srid: output_srs = SpatialReference(output_srid) else: output_srs = native_srs geometry_type = self._get_geometry_type(geofield) layer = lgdal.OGR_DS_CreateLayer(datasource, "lyr", output_srs, geometry_type, None) return layer, datasource
def MapaBeneficiarios(request): if request.user.is_authenticated(): from geo_liberty.models import Municipio unidades = UnidadeProducao.objects.all() taquarucu = Municipio.objects.filter(id = 4321329) ct = CoordTransform(SpatialReference('EPSG:4326'), SpatialReference('EPSG:900913')) for feat in unidades: feat.ponto.transform(ct) for feat in taquarucu: municipio = feat.mpoly municipio.transform(ct) return render_to_response('mapa_beneficiarios.html', RequestContext(request,{'unidades': unidades, 'municipio':municipio})) else: return render_to_response('login.html', RequestContext(request,{}))
def update_sedes_municipais(shapefilename, srid=4618): # dados de um shapefile de 2001 ds = DataSource(shapefilename) transform_coord = None if srid != SRID: transform_coord = CoordTransform(SpatialReference(srid), SpatialReference(SRID)) ct = 0 cta = 0 for f in ds[0]: ct += 1 cod = f.get('CODIGO') muns = Municipio.objects.extra( where=['CAST(id_ibge AS VARCHAR) ILIKE %s'], params=['%s%%' % cod]) if muns: if len(muns) > 1: print "Mais de 1 municipio para", cod for m in muns: print m.id_ibge, m else: g = f.geom g.srs = SpatialReference(srid) g.srid = srid if transform_coord: g.transform(transform_coord) print g.ewkt muns[0].sede = g.ewkt muns[0].save() cta += 1 else: print cod, "nao econtrado!" print "Atualizados", cta, "sedes" print "Total de", ct, "registros no shapefile"
def _create_layer(self, tmp_name, fieldmapping, geofield, output_srid, encoding="utf-8", layer_name=""): if hasattr(geofield, 'srid'): in_srs = SpatialReference(geofield.srid) else: in_srs = SpatialReference(geofield._srid) if output_srid: out_srs = SpatialReference(output_srid) else: out_srs = in_srs crs = from_epsg(out_srs.srid) properties = fieldmapping.get_fiona_schema() schema = {"geometry" : self._get_geometry_type(geofield), "properties": properties} shapefile = fiona.open(tmp_name, "w", driver=self.driver_name, crs=crs, schema=schema, encoding=encoding) return shapefile
def _get_geometry_value(self, item, geofield, in_srid, out_srid): geometry = getattr(item, geofield.name) if geometry: ogr_geom = geometry.ogr if out_srid and out_srid != in_srid: if type(out_srid) is int: out_srid = SpatialReference(out_srid) if type(in_srid) is int: in_srid = SpatialReference(in_srid) ct = CoordTransform(in_srid, out_srid) ogr_geom.transform(ct) return ogr_geom.geojson else: # skip return None