Exemple #1
0
    def parse_layer(self,shapefile, layername, fields_of_interest):
        ds = DataSource(shapefile)
        lyr = ds[0]
        num_feat = lyr.num_feat

        overwrite = True
        if overwrite:
            try:
                old_lyr = Layer.objects.get(name=layername)
                old_lyr.delete()
            except:
                pass
        try:
            the_layer = Layer(name=layername)
            the_layer.save()
        except:
            raise Exception('Unable to create layer named %s' % layername)

        wgs84 = SpatialReference(4326)
        pctdone = 0
        for feat in lyr:
            try:
                the_geometry = feat.geom.transform(wgs84,clone=True)
                the_feature = Feature(layer=the_layer, geom=the_geometry.wkt)
                the_feature.save()
            except:
                raise Exception('Unable to create feature')

            try:
                for fld in lyr.fields:
                    if fld in fields_of_interest or len(fields_of_interest) == 0:
                        the_attribute = Attribute(key=fld, value=str(feat[fld]), feature=the_feature)
                        the_attribute.save()
            except:
                raise Exception('Unable to create attribute')

            oldpctdone = pctdone
            pctdone = int((feat.fid * 100.) / float(num_feat))
            if pctdone > oldpctdone:
                print "Completed %d percent of %d features" % (pctdone, num_feat)
Exemple #2
0
    def parse_layer(self,rast, layername, srs):
        ds = gdal.Open(rast)
        if ds is None:
            raise Exception("Dataset is not valid")
        else:
            rast = os.path.abspath(rast)

        if srs:
            srscmdpart = "-a_srs '%s'" % srs
        else:
            srscmdpart = ''
            if ds.GetProjection() == '' or not ds.GetProjection():
                raise Exception("Looks like the raster doesn't have a projection defined - use --srs")

        # Create a new layer
        overwrite = True
        if overwrite:
            try:
                old_lyr = Layer.objects.get(name=layername)
                old_lyr.delete()
            except:
                pass
        the_layer = Layer(name=layername)
        the_layer.save()

        # Make a vrt copy of the dataset
        vrtpath = os.path.abspath(os.path.join(settings.MEDIA_ROOT,"xyquery_rasters",layername + ".vrt"))
        command = "gdal_translate %s -of VRT '%s' '%s'" % (srscmdpart, rast, vrtpath)
        output = Popen(command, shell=True).communicate()[0]

        ds = gdal.Open(vrtpath)
        if not ds or not os.path.exists(vrtpath):
            raise Exception("%s does not exist .. somthing went screwy in the gdal_translate command \n\n %s" % (vrtpath, command))
        del ds

        # Create a new raster model instance
        the_raster = Raster(layer=the_layer, filepath=vrtpath)
        the_raster.save()