Esempio n. 1
0
def getMapForm(shapefile):
    """ Devuelve un form. Subclase Form para editar las features del shapefile.
        El formulario tendrá un solo campo, 'geometría', que permite al usuario editar
        La geometría del feature.
    """

    geometryField = utils.calc_geometry_field(shapefile.geom_type)
    geometryType = utils.calcGeometryFieldType(shapefile.geom_type)

    if geometryType == "Point":
        adminType = PointAdmin
    elif geometryType == "LineString":
        adminType = LineStringAdmin
    elif geometryType == "Polygon":
        adminType = PolygonAdmin
    elif geometryType == "MultiPoint":
        adminType = MultiPointAdmin
    elif geometryType == "MultiLineString":
        adminType = MultiLineStringAdmin
    elif geometryType == "MultiPolygon":
        adminType = MultiPolygonAdmin
    elif geometryType == "GeometryCollection":
        adminType = GeometryCollectionAdmin

    adminInstance = adminType(Feature, admin.site)
    field = Feature._meta.get_field(geometryField)

    widgetType = adminInstance.get_map_widget(field)

    # Defina un formulario que encapsule el campo de edición deseado.

    class MapForm(forms.Form):
        geometry = forms.CharField(widget=widgetType(), label="")

    return MapForm
Esempio n. 2
0
def editFeature(request, shapefile_id, feature_id=None):
    """ Permite al usuario añadir o editar una feature del shapefile.
        el campo 'feature_id' será None if we are adding a new feature.
    """
    shapefile = Shapefile.objects.get(id=shapefile_id)

    if request.method == "POST" and "delete" in request.POST:
        # User clicked on the "Delete" button -> show "Delete Feature" page.
        return HttpResponseRedirect("/deleteFeature/" + shapefile_id + "/" +
                                    feature_id)

    geometryField = utils.calc_geometry_field(shapefile.geom_type)

    formType = shapefileEditor.getMapForm(shapefile)

    if feature_id == None:
        # Annadiendo una nueva feature.
        feature = Feature(shapefile=shapefile)
        attributes = []
    else:
        # Editando una feature.
        feature = Feature.objects.get(id=feature_id)

    # Toma los atributos para esta feature.

    attributes = []
    for attrValue in feature.attributevalue_set.all():
        attributes.append([attrValue.attribute.name, attrValue.value])
    attributes.sort()

    # Muestra el formulario

    if request.method == "GET":
        wkt = getattr(feature, geometryField)
        form = formType({'geometry': wkt})
        return render_to_response("editFeature.html", {
            'shapefile': shapefile,
            'form': form,
            'attributes': attributes
        })
    elif request.method == "POST":
        form = formType(request.POST)
        try:
            if form.is_valid():
                wkt = form.cleaned_data['geometry']
                setattr(feature, geometryField, wkt)
                feature.save()
                # Devuelve al usuario a la pagina de seleccion de features.
                return HttpResponseRedirect("/edit/" + shapefile_id)
        except ValueError:
            pass

        return render_to_response("editFeature.html", {
            'shapefile': shapefile,
            'form': form,
            'attributes': attributes
        })
Esempio n. 3
0
def edit_feature(request, shapefile_id, feature_id=None):
    if request.method == "POST" and "delete" in request.POST:
        return HttpResponseRedirect("/delete_feature/" + shapefile_id + "/" +
                                    feature_id)
    try:
        shapefile = Shapefile.objects.get(id=shapefile_id)
    except ShapeFile.DoesNotExist:
        return HttpResponseNotFound()

    if feature_id == None:
        feature = Feature(shapefile=shapefile)
    else:
        try:
            feature = Feature.objects.get(id=feature_id)
        except Feature.DoesNotExist:
            return HttpResponseNotFound()
    attributes = []
    for attr_value in feature.attributevalue_set.all():
        attributes.append([attr_value.attribute.name, attr_value.value])
        attributes.sort()
    if request.method == "GET":
        form = MyForm()
        return render(request, "template.html", {'form': form})
    elif request.method == "POST":
        form = MyForm(request.POST)
        if form.is_valid():
            # Extract and save the form's contents here...
            return HttpResponseRedirect("/somewhere/else")
        return render(request, "template.html", {'form': form})
    geometry_field = utils.calc_geometry_field(shapefile.geom_type)
    form_class = utils.get_map_form(shapefile)
    if request.method == "GET":
        wkt = getattr(feature, geometry_field)
        form = form_class({'geometry': wkt})
        return render(request, "edit_feature.html", {
            'shapefile': shapefile,
            'form': form,
            'attributes': attributes
        })
    elif request.method == "POST":
        form = form_class(request.POST)
        try:
            if form.is_valid():
                wkt = form.cleaned_data['geometry']
                setattr(feature, geometry_field, wkt)
                feature.save()
                return HttpResponseRedirect("/edit/" + shapefile_id)
        except ValueError:
            pass
        return render(request, "edit_feature.html", {
            'shapefile': shapefile,
            'form': form,
            'attributes': attributes
        })
Esempio n. 4
0
def edit_feature(request, shapefile_id, feature_id=None):
  if request.method == "POST" and "delete" in request.POST:
    return HttpResponseRedirect("/delete_feature/" +
                                shapefile_id+"/"+feature_id)

  try:
    shapefile = Shapefile.objects.get(id=shapefile_id)
  except ShapeFile.DoesNotExist:
    return HttpResponseNotFound()

  if feature_id == None:
    feature = Feature(shapefile=shapefile)
  else:
    try:
      feature = Feature.objects.get(id=feature_id)
    except Feature.DoesNotExist:
      return HttpResponseNotFound()

  attributes = []
  for attr_value in feature.attributevalue_set.all():
    attributes.append([attr_value.attribute.name,
                       attr_value.value])
  attributes.sort()

  geometry_field = \
       utils.calc_geometry_field(shapefile.geom_type)
  form_class = utils.get_map_form(shapefile)

  if request.method == "GET":
    wkt = getattr(feature, geometry_field)
    form = form_class({'geometry' : wkt})

    return render(request, "edit_feature.html",
                  {'shapefile'  : shapefile,
                   'form'       : form,
                   'attributes' : attributes})
  elif request.method == "POST":
    form = form_class(request.POST)
    try:
      if form.is_valid():
        wkt = form.cleaned_data['geometry']
        setattr(feature, geometry_field, wkt)
        feature.save()
        return HttpResponseRedirect("/edit/" +
                                    shapefile_id)
    except ValueError:
      pass

    return render(request, "edit_feature.html",
                  {'shapefile'  : shapefile,
                   'form'       : form,
                   'attributes' : attributes})
Esempio n. 5
0
def export_data(shapefile):
    dst_dir = tempfile.mkdtemp()
    dst_file = os.path.join(dst_dir, shapefile.filename)
    dst_spatial_ref = osr.SpatialReference()
    dst_spatial_ref.ImportFromWkt(shapefile.srs_wkt)
    driver = ogr.GetDriverByName("ESRI Shapefile")
    datasource = driver.CreateDataSource(dst_file)
    layer = datasource.CreateLayer(shapefile.filename, dst_spatial_ref)
    for attr in shapefile.attribute_set.all():
        field = ogr.FieldDefn(attr.name, attr.type)
        field.SetWidth(attr.width)
        field.SetPrecision(attr.precision)
        layer.CreateField(field)
    src_spatial_ref = osr.SpatialReference()
    src_spatial_ref.ImportFromEPSG(4326)
    coord_transform = osr.CoordinateTransformation(src_spatial_ref,
                                                   dst_spatial_ref)
    geom_field = utils.calc_geometry_field(shapefile.geom_type)
    for feature in shapefile.feature_set.all():
        geometry = getattr(feature, geom_field)
        geometry = utils.unwrap_geos_geometry(geometry)
        dst_geometry = ogr.CreateGeometryFromWkt(geometry.wkt)
        dst_geometry.Transform(coord_transform)
        dst_feature = ogr.Feature(layer.GetLayerDefn())
        dst_feature.SetGeometry(dst_geometry)
        for attr_value in feature.attributevalue_set.all():
            utils.set_ogr_feature_attribute(attr_value.attribute,
                                            attr_value.value, dst_feature)
        layer.CreateFeature(dst_feature)
    layer = None
    datasource = None
    temp = tempfile.TemporaryFile()
    zip = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)

    shapefile_name = os.path.splitext(shapefile.filename)[0]

    for fName in os.listdir(dst_dir):
        zip.write(os.path.join(dst_dir, fName), fName)
    zip.close()
    shutil.rmtree(dst_dir)
    temp.flush()
    temp.seek(0)
    response = FileResponse(temp)
    response['Content-type'] = "application/zip"
    response[
        'Content-Disposition'] = "attachment; filename=" + shapefile_name + ".zip"
    return response
Esempio n. 6
0
def tile(request, version, shapefile_id, zoom, x, y):
    try:
        # Parse and check our parameters.

        if version != "1.0":
            raise Http404

        try:
            shapefile = Shapefile.objects.get(id=shapefile_id)
        except Shapefile.DoesNotExist:
            raise Http404

        zoom = int(zoom)
        x = int(x)
        y = int(y)

        if zoom < 0 or zoom > MAX_ZOOM_LEVEL:
            raise Http404

        xExtent = _unitsPerPixel(zoom) * TILE_WIDTH
        yExtent = _unitsPerPixel(zoom) * TILE_HEIGHT

        minLong = x * xExtent - 180.0
        minLat = y * yExtent - 90.0
        maxLong = minLong + xExtent
        maxLat = minLat + yExtent

        if (minLong < -180 or maxLong > 180 or minLat < -90 or maxLat > 90):
            raise Http404

        # Set up the map.

        map = mapnik.Map(TILE_WIDTH, TILE_HEIGHT, "+proj=longlat +datum=WGS84")
        map.background = mapnik.Color("#7391ad")

        # Define the base layer.

        dbSettings = settings.DATABASES['default']
        datasource = \
            mapnik.PostGIS(user=dbSettings['USER'],
                           password=dbSettings['PASSWORD'],
                           dbname=dbSettings['NAME'],
                           table='tms_basemap',
                           srid=4326,
                           geometry_field="geometry",
                           geometry_table='tms_basemap')

        baseLayer = mapnik.Layer("baseLayer")
        baseLayer.datasource = datasource
        baseLayer.styles.append("baseLayerStyle")

        rule = mapnik.Rule()

        rule.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color("#b5d19c")))
        rule.symbols.append(mapnik.LineSymbolizer(mapnik.Color("#404040"),
                                                  0.2))

        style = mapnik.Style()
        style.rules.append(rule)

        map.append_style("baseLayerStyle", style)
        map.layers.append(baseLayer)

        # Define the feature layer.

        geometry_field = utils.calc_geometry_field(shapefile.geom_type)

        query = '(select ' + geometry_field \
              + ' from "shared_feature" where' \
              + ' shapefile_id=' + str(shapefile.id) + ') as geom'

        datasource = \
            mapnik.PostGIS(user=dbSettings['USER'],
                           password=dbSettings['PASSWORD'],
                           dbname=dbSettings['NAME'],
                           table=query,
                           srid=4326,
                           geometry_field=geometry_field,
                           geometry_table='shared_feature')

        featureLayer = mapnik.Layer("featureLayer")
        featureLayer.datasource = datasource
        featureLayer.styles.append("featureLayerStyle")

        rule = mapnik.Rule()

        if shapefile.geom_type in ["Point", "MultiPoint"]:
            rule.symbols.append(mapnik.PointSymbolizer())
        elif shapefile.geom_type in ["LineString", "MultiLineString"]:
            rule.symbols.append(
                mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5))
        elif shapefile.geom_type in ["Polygon", "MultiPolygon"]:
            rule.symbols.append(
                mapnik.PolygonSymbolizer(mapnik.Color("#f7edee")))
            rule.symbols.append(
                mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5))

        style = mapnik.Style()
        style.rules.append(rule)

        map.append_style("featureLayerStyle", style)
        map.layers.append(featureLayer)

        # Finally, render the map tile.

        map.zoom_to_box(mapnik.Box2d(minLong, minLat, maxLong, maxLat))
        image = mapnik.Image(TILE_WIDTH, TILE_HEIGHT)
        mapnik.render(map, image)
        imageData = image.tostring('png')

        return HttpResponse(imageData, content_type="image/png")
    except:
        traceback.print_exc()
        return HttpResponse("Error")
def import_data(request, shapefile, character_encoding):
    #return "More to come..."
    fd,fname = tempfile.mkstemp(suffix=".zip")

# tempfile.mkstemp() returns both a file descriptor and a filename, we call
# os.close(fd) to close the file descriptor. This allows us to reopen the
# file using open() and write to it in the normal way.
    os.close(fd)

    f = open(fname, "wb")
    for chunk in shapefile.chunks():
        f.write(chunk)
    f.close()

# Use the Python standard library's zipfile module to check the
# contents of the uploaded ZIP archive, and return a suitable error message
# if something is wrong

    if not zipfile.is_zipfile(fname):
        os.remove(fname)
        return "Not a valid zip archive."
    zip = zipfile.ZipFile(fname)
    required_suffixes = [".shp", ".shx", ".dbf", ".prj"]
    has_suffix = {}
    for suffix in required_suffixes:
        has_suffix[suffix] = False

    for info in zip.infolist():
        extension = os.path.splitext(info.filename)[1].lower()
        if extension in required_suffixes:
            has_suffix[extension] = True

    for suffix in required_suffixes:
        if not has_suffix[suffix]:
            zip.close()
# Delete the temporary file before returning
# an error message, so that we don't leave temporary files lying around
            os.remove(fname)
            return "Archive missing required "+suffix+" file."
# When it's known that the uploaded file is a valid ZIP archive containing
# the files that make up a shapefile, extract these files and store them
# into a temporary directory

    shapefile_name = None
    dst_dir = tempfile.mkdtemp()
    for info in zip.infolist():
        if info.filename.endswith(".shp"):
            shapefile_name = info.filename
        dst_file = os.path.join(dst_dir, info.filename)
        f = open(dst_file, "wb")
        f.write(zip.read(info.filename))
        f.close()
    zip.close()

    
# Open the shapefile
    try:
        datasource = ogr.Open(os.path.join(dst_dir, shapefile_name))
        layer = datasource.GetLayer(0)
        shapefileOK = True
    except:
        traceback.print_exc()
        shapefileOK = False

# if something goes wrong - clean up our temporary files and return a
# suitable error message. 
        if not shapefileOK:
            os.remove(fname)
            shutil.rmtree(dst_dir)
            return "Not a valid shapefile."

# If the shapefile was opened sucessfully - read the data out
# of it. Create the Shapefile object to represent this imported shapefile.
# Get the spatial reference from the shapefile's layer, and then store
# the shapefile's name, spatial reference, and encoding into a Shapefile
# object. The geom_type field is supposed to hold the name of the geometry
# type that this shapefile holds but can't get the name of the geometry
# directly using OGR. Need to implement our own version of
# OGRGeometryTypeToName(). See utils.py module in shared app directory


    src_spatial_ref = layer.GetSpatialRef()
    geometry_type = layer.GetLayerDefn().GetGeomType()
    geometry_name = utils.ogr_type_to_geometry_name(geometry_type)
    curr_user = request.user

    shapefile = Shapefile(filename=shapefile_name,
                          srs_wkt=src_spatial_ref.ExportToWkt(),
                          geom_type=geometry_name,
                          encoding=character_encoding,
                          owner=curr_user)
    shapefile.save()

# Create Attribute objects describing the shapefile's attributes
# Save the Attribute objects into a database and create a
# separate list of these attributes in a variable named attributes.
# Needed for import the attribute values for each feature.

    attributes = []
    layer_def = layer.GetLayerDefn()
    for i in range(layer_def.GetFieldCount()):
        field_def = layer_def.GetFieldDefn(i)
        attr = Attribute(
                shapefile=shapefile,
                name=field_def.GetName(),
                type=field_def.GetType(),
                width=field_def.GetWidth(),
                precision=field_def.GetPrecision())
        attr.save()
        attributes.append(attr)

# Extract the shapefile's features and store them as Feature objects
# in the database. Because the shapefile's features can be in any spatial
# reference, we need to transform them into our internal spatial reference
# system (EPSG 4326, unprojected latitude, and longitude values) before we
# can store them. To do this, use an OGR CoordinateTransformation() object.
# GEOS geometry object caan be stored into the Feature object.

    dst_spatial_ref = osr.SpatialReference()
    dst_spatial_ref.ImportFromEPSG(4326)
    coord_transform = osr.CoordinateTransformation(src_spatial_ref,
                                     dst_spatial_ref)
    for i in range(layer.GetFeatureCount()):
        src_feature = layer.GetFeature(i)
        # src_name = src_feature.name;
        src_geometry = src_feature.GetGeometryRef()
        src_geometry.Transform(coord_transform)
        geometry = GEOSGeometry(src_geometry.ExportToWkt())
# See wrap geometry in utils: it distinguish polygons and multipoligon,
# linestring and multilinestrings
        geometry = utils.wrap_geos_geometry(geometry)

# Can't simply use the geometry name to identify the field because
# sometimes have to wrap up geometries. See utils.py.

        geometry_field = utils.calc_geometry_field(geometry_name)

# Store the feature's geometry into a Feature object within the database
# Note: Use keyword arguments (**args) to create the Feature object.
# This lets to store the geometry into the correct field of the Feature
# object with a minimum of fuss. 

        args = {}
        args['shapefile'] = shapefile
        args[geometry_field] = geometry
        feature = Feature(**args)
        feature.save()

        for attr in attributes:
            success,result = utils.getOGRFeatureAttribute(
                    attr,
                    src_feature,
                    character_encoding)
            if not success:
               os.remove(fname)
               shutil.rmtree(dst_dir)
               shapefile.delete()
               return result

            attr_value = AttributeValue(
                    feature=feature,
                    attribute=attr,
                    value=result)
            attr_value.save()

    os.remove(fname)
    shutil.rmtree(dst_dir)
    return None
def import_data(shapefile, character_encoding):

    # Save the uploaded file into a temporary file on disk.

    fd,fname = tempfile.mkstemp(suffix=".zip")
    os.close(fd)

    f = open(fname, "wb")
    for chunk in shapefile.chunks():
        f.write(chunk)
    f.close()

    # Check that the uploaded file is a zip archive.

    if not zipfile.is_zipfile(fname):
        os.remove(fname)
        return "Not a valid zip archive."

    zip = zipfile.ZipFile(fname)

    # Check that the zip archive contains the required parts of a shapefile.

    required_suffixes = [".shp", ".shx", ".dbf", ".prj"]
    has_suffix = {}
    for suffix in required_suffixes:
        has_suffix[suffix] = False

    for info in zip.infolist():
        extension = os.path.splitext(info.filename)[1].lower()
        if extension in required_suffixes:
            has_suffix[extension] = True

    for suffix in required_suffixes:
        if not has_suffix[suffix]:
            zip.close()
            os.remove(fname)
            return "Archive mising required " + suffix + " file."

    # Extract the contents of the zip archive.

    shapefile_name = None
    dst_dir = tempfile.mkdtemp()
    for info in zip.infolist():
        if info.filename.endswith(".shp"):
            shapefile_name = info.filename

        dst_file = os.path.join(dst_dir, info.filename)
        f = open(dst_file, "wb")
        f.write(zip.read(info.filename))
        f.close()

    zip.close()

    # Open the shapefile.

    try:
        datasource = ogr.Open(os.path.join(dst_dir,
                                           shapefile_name))
        layer = datasource.GetLayer(0)
        shapefile_ok = True
    except:
        traceback.print_exc()
        shapefile_ok = False

    if not shapefile_ok:
        os.remove(fname)
        shutil.rmtree(dst_dir)
        return "Not a valid shapefile."

    # Create our Shapefile object to represent the imported shapefile.

    src_spatial_ref = layer.GetSpatialRef()

    geometry_type = layer.GetLayerDefn().GetGeomType()
    geometry_name = utils.ogr_type_to_geometry_name(geometry_type)

    shapefile = Shapefile(filename=shapefile_name,
                          srs_wkt=src_spatial_ref.ExportToWkt(),
                          geom_type=geometry_name,
                          encoding=character_encoding)
    shapefile.save()

    # Store the shapefile's attribute definitions into the database.

    attributes = []
    layer_def = layer.GetLayerDefn()
    for i in range(layer_def.GetFieldCount()):
        field_def = layer_def.GetFieldDefn(i)
        attr = Attribute(shapefile=shapefile,
                         name=field_def.GetName(),
                         type=field_def.GetType(),
                         width=field_def.GetWidth(),
                         precision=field_def.GetPrecision())
        attr.save()
        attributes.append(attr)

    # Set up a coordinate transformation to convert from the shapefile's
    # coordinate system into EPSG 4326 (unprojected lat/long coordinates).

    dst_spatial_ref = osr.SpatialReference()
    dst_spatial_ref.ImportFromEPSG(4326)

    coord_transform = osr.CoordinateTransformation(src_spatial_ref,
                                                   dst_spatial_ref)

    # Process each feature in turn.

    for i in range(layer.GetFeatureCount()):
        src_feature = layer.GetFeature(i)

        # Transform this feature's geometry into EPSG 4326.

        src_geometry = src_feature.GetGeometryRef()
        src_geometry.Transform(coord_transform)
        geometry = GEOSGeometry(src_geometry.ExportToWkt())

        # If necessary, wrap this geometry so that all features have the same
        # geometry type.

        geometry = utils.wrap_geos_geometry(geometry)

        # Calculate the field in the Feature object which will hold the
        # imported feature.

        geometry_field = utils.calc_geometry_field(geometry_name)

        # Create a new Feature object to hold this feature's geometry.

        args = {}
        args['shapefile'] = shapefile
        args[geometry_field] = geometry
        feature = Feature(**args)
        feature.save()

        # Store the feature's attribute values into the database.

        for attr in attributes:
            success,result = utils.get_ogr_feature_attribute(
                                      attr, src_feature,
                                      character_encoding)
            if not success:
                os.remove(fname)
                shutil.rmtree(dst_dir)
                shapefile.delete()
                return result

            attr_value = AttributeValue(feature=feature,
                                        attribute=attr,
                                        value=result)
            attr_value.save()

    # Finally, clean up.

    os.remove(fname)
    shutil.rmtree(dst_dir)
    return None
Esempio n. 9
0
def import_data(shapefile):
    # Copia el archivo zip en un archivo temporal

    fd,fname = tempfile.mkstemp(suffix=".zip")
    os.close(fd)

    f = open(fname, "wb")
    for chunk in shapefile.chunks():
        f.write(chunk)
    f.close()

    # Se abre el zip y se chequea su contenido.

    if not zipfile.is_zipfile(fname):
        os.remove(fname)
        return "No es un archivo zip válido."

    zip = zipfile.ZipFile(fname)
    
    #Diferenciacion de los archivos requeridos segun el formato del archivo de entrada

    es_shp = False
    for info in zip.infolist():
        extension = os.path.splitext(info.filename)[1].lower()
        if extension == '.shp':
            es_shp = True
    
    #Sie s un shp, se aplica una comprobación de que todos los archivos necearios estén en el zip
    if es_shp: 
        required_suffixes = [".shp", ".shx", ".dbf", ".prj"]
        hasSuffix = {}
        for suffix in required_suffixes:
            hasSuffix[suffix] = False
    
        for info in zip.infolist():
            extension = os.path.splitext(info.filename)[1].lower()
            if extension in required_suffixes:
                hasSuffix[extension] = True
            else:
                print "Archivo extraño: " + info.filename
    
        for suffix in required_suffixes:
            if not hasSuffix[suffix]:
                zip.close()
                os.remove(fname)
                return "No se encuentra el archivo " + suffix + " requerido"
            
    else:
        zip.close()
    
    # Descomprime el zip en un directorio temporal.
    # Se toma el nombre del archivo principal.
        
    zip = zipfile.ZipFile(fname)
    shapefileName = None
    dirname = tempfile.mkdtemp()
    for info in zip.infolist():
        if info.filename.endswith(".shp") and es_shp:
            shapefileName = info.filename
        if not es_shp:
            shapefileName = info.filename
            
        dst_file = os.path.join(dirname, info.filename)
        f = open(dst_file, "wb")
        f.write(zip.read(info.filename))
        f.close()
    zip.close()

    # Intenta abrir el archivo

    try:
        datasource  = ogr.Open(os.path.join(dirname, shapefileName))
        layer       = datasource.GetLayer(0)
        shapefileOK = True
    except:
        traceback.print_exc()
        shapefileOK = False

    if not shapefileOK:
        os.remove(fname)
        shutil.rmtree(dirname)
        return "No es un archivo válido."

    # Importar los datos del shapefile abierto.
    
    feature1 = layer.GetFeature(0)
    tipo_geometria = feature1.geometry().GetGeometryType()
    feature1.Destroy()
    #geometryType  = layer.GetLayerDefn().GetGeomType()
    geometryName = ogr.GeometryTypeToName(tipo_geometria)
    geometryName = geometryName.replace(" ", "")
    src_spatial_ref = layer.GetSpatialRef()
    dst_spatial_ref = osr.SpatialReference()
    dst_spatial_ref.ImportFromEPSG(4326)         #Aqui se define que sistema de coordenadas se le asigna en la BD

    shapefile = Shapefile(filename=shapefileName,
                          srs_wkt=src_spatial_ref.ExportToWkt(),
                          geom_type=geometryName)
    shapefile.save()

    attributes = []
    layerDef = layer.GetLayerDefn()
    for i in range(layerDef.GetFieldCount()):
        fieldDef = layerDef.GetFieldDefn(i)
        attr = Attribute(shapefile=shapefile,
                         name=fieldDef.GetName(),
                         type=fieldDef.GetType(),
                         width=fieldDef.GetWidth(),
                         precision=fieldDef.GetPrecision())
        attr.save()
        attributes.append(attr)
    #layerDef.Destroy()    
    
    coordTransform = osr.CoordinateTransformation(src_spatial_ref,
                                                  dst_spatial_ref)
        
    for i in range(layer.GetFeatureCount()):
        srcFeature = layer.GetFeature(i)
        srcGeometry = srcFeature.GetGeometryRef()
        srcGeometry.Transform(coordTransform)
        geometry = GEOSGeometry(srcGeometry.ExportToWkt())
        geometry = utils.wrap_geos_geometry(geometry)
        geometryField = utils.calc_geometry_field(geometryName)
        args = {}
        args['shapefile'] = shapefile
        args[geometryField] = geometry
        feature = Feature(**args)
        feature.save()
        
        for attr in attributes:
            success,result = utils.get_ogr_feature_attribute(attr, srcFeature)
            #if not success:
                #os.remove(fname)
                #print dirname
                #shutil.rmtree(dirname)
                #shapefile.delete()
                #return result
            if success:
                attrValue = AttributeValue(feature=feature, attribute=attr, value=result)
                attrValue.save()
        
    # Finalmente, limpiarlo todo.
    datasource.Destroy()
    os.remove(fname)
    print dirname
    shutil.rmtree(dirname)

    return None # Exito.
Esempio n. 10
0
def export_data(shapefile, dst_spatial_ref, driver, extension):

    shapefile.filename = os.path.splitext(shapefile.filename)[0] + str(extension)
    
    # Crea el shapefile.

    dst_dir = tempfile.mkdtemp()
    dst_file = str(os.path.join(dst_dir, shapefile.filename))

    #dst_spatial_ref = osr.SpatialReference()           #Comentado porque recibe el src de la template
    #dst_spatial_ref.ImportFromEPSG(dst_epsg)
    #dst_spatial_ref.ImportFromWkt(shapefile.srs_wkt)
    
    #driver = ogr.GetDriverByName("ESRI Shapefile")     #Comentado porque recibe el driver de la template
    datasource = driver.CreateDataSource(dst_file)

    layer = datasource.CreateLayer(str(shapefile.filename), dst_spatial_ref)

    # Define los atributos del shapefile.

    for attr in shapefile.attribute_set.all():
        field = ogr.FieldDefn(str(attr.name), attr.type)
        field.SetWidth(attr.width)
        field.SetPrecision(attr.precision)
        layer.CreateField(field)

    # Crea el sistema de coodenadas.

    src_spatial_ref = osr.SpatialReference()
    src_spatial_ref.ImportFromEPSG(4326)

    coord_transform = osr.CoordinateTransformation(
                          src_spatial_ref, dst_spatial_ref)

    # Calcula que campo de geometria contiene la geometria del shapefile's.

    geom_field = utils.calc_geometry_field(shapefile.geom_type)

    # Exporta las features.

    for feature in shapefile.feature_set.all():
        geometry = getattr(feature, geom_field)
        geometry = utils.unwrap_geos_geometry(geometry)

        dst_geometry = ogr.CreateGeometryFromWkt(geometry.wkt)
        dst_geometry.Transform(coord_transform)

        dst_feature = ogr.Feature(layer.GetLayerDefn())
        dst_feature.SetGeometry(dst_geometry)

        for attr_value in feature.attributevalue_set.all():
            utils.set_ogr_feature_attribute(
                    attr_value.attribute,
                    attr_value.value,
                    dst_feature)

        layer.CreateFeature(dst_feature)

    layer      = None
    datasource = None

    # Compreime el shapefile como archivo ZIP.

    temp = tempfile.TemporaryFile()
    zip = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)

    shapefile_name = os.path.splitext(shapefile.filename)[0]

    for fName in os.listdir(dst_dir):
        zip.write(os.path.join(dst_dir, fName), fName)

    zip.close()
    shutil.rmtree(dst_dir)

    # Devuelve el archivo ZIP.

    temp.flush()
    temp.seek(0)

    response = FileResponse(temp)
    response['Content-type'] = "application/zip"
    response['Content-Disposition'] = \
        "attachment; filename=" + shapefile_name + ".zip"
    return response
def export_data(shapefile):
# return "More to come..."
# Create a temporary directory to hold the shapefile's contents
    dst_dir = tempfile.mkdtemp()
    dst_file = str(os.path.join(dst_dir, shapefile.filename))
# Create a spatial reference for the shapefile to use, and 
# set up the shapefile's datasource and layer
    dst_spatial_ref = osr.SpatialReference()
    dst_spatial_ref.ImportFromWkt(shapefile.srs_wkt)
    driver = ogr.GetDriverByName("ESRI Shapefile")
    datasource = driver.CreateDataSource(dst_file)
    layer = datasource.CreateLayer(str(shapefile.filename),
                                   dst_spatial_ref)

# Define the various fields which will hold the shapefile's attributes.
# Django makes iterating over the shapefile's attributes 

    for attr in shapefile.attribute_set.all():
        field = ogr.FieldDefn(str(attr.name), attr.type)
        field.SetWidth(attr.width)
        field.SetPrecision(attr.precision)
        layer.CreateField(field)


# To transform the shapefile's features from the spatial reference 
# used internally (EPSG 4326) into the shapefile's own spatial reference.
# First, need to set up an osr.CoordinateTransformation object to do the transformation
    src_spatial_ref = osr.SpatialReference()
    src_spatial_ref.ImportFromEPSG(4326)
    coord_transform = osr.CoordinateTransformation(
                           src_spatial_ref, dst_spatial_ref)
#  Determine which geometry field in the Feature object holds the feature's geometry data
    geom_field = \
          utils.calc_geometry_field(shapefile.geom_type)

#  Exporting the shapefile's features
    for feature in shapefile.feature_set.all():
        geometry = getattr(feature, geom_field)

#  Need to unwrap the geometry so that features that have only one Polygon
#  or LineString in their geometries are saved as Polygons and LineStrings
#  rather than MultiPolygons and MultiLineStrings.
#  See utils.py function for unwrapping
        geometry = utils.unwrap_geos_geometry(geometry)

# Convert feature's geometry back into an OGR geometry again, 
# transform it into the shapefile's own spatial reference system, 
# and create an OGR feature using that geometry:
        dst_geometry = ogr.CreateGeometryFromWkt(geometry.wkt)
        dst_geometry.Transform(coord_transform)
        dst_feature = ogr.Feature(layer.GetLayerDefn())
        dst_feature.SetGeometry(dst_geometry)


# Save the attribute values associated with each feature by
# storing the string value into the OGR attribute field. See utils.py

        for attr_value in feature.attributevalue_set.all():
            utils.set_ogr_feature_attribute(
                        attr_value.attribute,
                        attr_value.value,
                        dst_feature,
                        shapefile.encoding)


# Add the feature to the layer and call the Destroy() method to
# save the feature (and then the layer) into the shapefile

        layer.CreateFeature(dst_feature)
        dst_feature.Destroy()
    datasource.Destroy()


# Compress exported data into an OGR shapefile into a ZIP archive
# Note: a temporary file, named temp, is used to store the ZIP
# archive's contents. It'll be returned to the user's web browser
# once the export process has finished


    temp = tempfile.TemporaryFile()
    zip = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    
    shapefile_base = os.path.splitext(dst_file)[0]
    shapefile_name = os.path.splitext(shapefile.filename)[0]
    
    for fName in os.listdir(dst_dir):
        zip.write(os.path.join(dst_dir, fName), fName)
    zip.close()

# Deleting the shapefile that was created earlier
    shutil.rmtree(dst_dir)

# Send the ZIP archive to the user's web browser so that it can be
# downloaded onto the user's computer. To do this: create an
# HttpResponse object which includes a Django FileWrapper object
# to attach the ZIP archive to the HTTP response

    f = FileWrapper(temp)
    response = HttpResponse(f, content_type="application/zip")
    response['Content-Disposition'] = \
        "attachment; filename=" + shapefile_name + ".zip"
    response['Content-Length'] = temp.tell()
    temp.seek(0)
    return response
def export_data(shapefile):

    # Create the shapefile.

    dst_dir = tempfile.mkdtemp()
    dst_file = os.path.join(dst_dir, shapefile.filename)

    dst_spatial_ref = osr.SpatialReference()
    dst_spatial_ref.ImportFromWkt(shapefile.srs_wkt)

    driver = ogr.GetDriverByName("ESRI Shapefile")
    datasource = driver.CreateDataSource(dst_file)
    layer = datasource.CreateLayer(shapefile.filename,
                                   dst_spatial_ref)

    # Define the shapefile's attributes.

    for attr in shapefile.attribute_set.all():
        field = ogr.FieldDefn(attr.name, attr.type)
        field.SetWidth(attr.width)
        field.SetPrecision(attr.precision)
        layer.CreateField(field)

    # Create our coordinate transformation.

    src_spatial_ref = osr.SpatialReference()
    src_spatial_ref.ImportFromEPSG(4326)

    coord_transform = osr.CoordinateTransformation(
                          src_spatial_ref, dst_spatial_ref)

    # Calculate which geometry field holds the shapefile's geometry.

    geom_field = utils.calc_geometry_field(shapefile.geom_type)

    # Export the shapefile's features.

    for feature in shapefile.feature_set.all():
        geometry = getattr(feature, geom_field)
        geometry = utils.unwrap_geos_geometry(geometry)

        dst_geometry = ogr.CreateGeometryFromWkt(geometry.wkt)
        dst_geometry.Transform(coord_transform)

        dst_feature = ogr.Feature(layer.GetLayerDefn())
        dst_feature.SetGeometry(dst_geometry)

        for attr_value in feature.attributevalue_set.all():
            utils.set_ogr_feature_attribute(
                    attr_value.attribute,
                    attr_value.value,
                    dst_feature)

        layer.CreateFeature(dst_feature)

    layer      = None
    datasource = None

    # Compress the shapefile as a ZIP archive.

    temp = tempfile.TemporaryFile()
    zip = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)

    shapefile_name = os.path.splitext(shapefile.filename)[0]

    for fName in os.listdir(dst_dir):
        zip.write(os.path.join(dst_dir, fName), fName)

    zip.close()
    shutil.rmtree(dst_dir)

    # Return the ZIP archive back to the caller.

    temp.flush()
    temp.seek(0)

    response = FileResponse(temp)
    response['Content-type'] = "application/zip"
    response['Content-Disposition'] = \
        "attachment; filename=" + shapefile_name + ".zip"
    return response
def export_data(shapefile):

    # Create a temporary directory to hold our shapefile.

    dst_dir = tempfile.mkdtemp()
    dst_file = str(os.path.join(dst_dir, shapefile.filename))

    # Create the shapefile and its associated spatial reference.

    dst_spatial_ref = osr.SpatialReference()
    dst_spatial_ref.ImportFromWkt(shapefile.srs_wkt)

    driver = ogr.GetDriverByName("ESRI Shapefile")
    datasource = driver.CreateDataSource(dst_file)
    layer = datasource.CreateLayer(str(shapefile.filename),
                                   dst_spatial_ref)

    # Define the various fields which will hold the shapefile's attributes.

    for attr in shapefile.attribute_set.all():
        field = ogr.FieldDefn(str(attr.name), attr.type)
        field.SetWidth(attr.width)
        field.SetPrecision(attr.precision)
        layer.CreateField(field)

    # Setup a coordinate transformation to convert from our internal spatial
    # reference system to the shapefile's original SRS.

    src_spatial_ref = osr.SpatialReference()
    src_spatial_ref.ImportFromEPSG(4326)

    coord_transform = osr.CoordinateTransformation(src_spatial_ref,
                                                   dst_spatial_ref)

    # See which field in the Feature object holds the feature's geometry.

    geom_field = utils.calc_geometry_field(shapefile.geom_type)

    # Start exporting the shapefile's contents.

    for feature in shapefile.feature_set.all():
        geometry = getattr(feature, geom_field)

        # If necessary, unwrap the geometry again.

        geometry = utils.unwrap_geos_geometry(geometry)

        # Convert the geometry into an OGR geometry object, and transform it
        # into the shapefile's original spatial reference system.

        dst_geometry = ogr.CreateGeometryFromWkt(geometry.wkt)
        dst_geometry.Transform(coord_transform)

        dst_feature = ogr.Feature(layer.GetLayerDefn())
        dst_feature.SetGeometry(dst_geometry)

        # Save the feature's attributes into the shapefile.

        for attr_value in feature.attributevalue_set.all():
            utils.set_ogr_feature_attribute(attr_value.attribute,
                                            attr_value.value,
                                            dst_feature,
                                            shapefile.encoding)

        # Finally, save the feature into the shapefile.

        layer.CreateFeature(dst_feature)
        dst_feature.Destroy()

    # Close the shapefile.

    datasource.Destroy()

    # Compress the shapefile into a ZIP archive.

    temp = tempfile.TemporaryFile()
    zip = zipfile.ZipFile(temp, "w", zipfile.ZIP_DEFLATED)

    shapefile_base = os.path.splitext(dst_file)[0]
    shapefile_name = os.path.splitext(shapefile.filename)[0]

    for fName in os.listdir(dst_dir):
        zip.write(os.path.join(dst_dir, fName), fName)

    zip.close()

    # Delete the shapefile directory.

    shutil.rmtree(dst_dir)

    # Finally, wrap the compressed ZIP archive in a FileWrapper so it can be
    # sent back to the user's web browser.

    f = FileWrapper(temp)
    response = HttpResponse(f, content_type="application/zip")
    response['Content-Disposition'] = \
        "attachment; filename=" + shapefile_name + ".zip"
    response['Content-Length'] = temp.tell()
    temp.seek(0)
    return response
Esempio n. 14
0
def tile(request, version, shapefile_id, zoom, x, y):
    try:
        if version != "1.0":
            raise Http404
        try:    
        
            shapefile = Shapefile.objects.get(id=shapefile_id)
        except Shapefile.DoesNotExist:
            raise Http404
                
        zoom = int(zoom)
        x = int(x)
        y = int(y)
        
        if zoom < 0 or zoom > MAX_ZOOM_LEVEL:
            raise Http404
        
        xExtent = _unitsPerPixel(zoom) * TILE_WIDTH
        yExtent = _unitsPerPixel(zoom) * TILE_HEIGHT

        minLong = x * xExtent - 180.0
        minLat  = y * yExtent - 90.0
        maxLong = minLong + xExtent
        maxLat  = minLat  + yExtent

        if (minLong < -180 or maxLong > 180 or
            minLat < -90 or maxLat > 90):
            print "Map extent out of bounds:",minLong,minLat,maxLong,maxLat
            raise Http404
        
        
        
        #######################################################  
          
        map = mapnik.Map(TILE_WIDTH, TILE_HEIGHT,
                         str("+proj=longlat +datum=WGS84"))
        map.background = mapnik.Color(str("#7391ad"))
        
        dbSettings = settings.DATABASES['default']
        datasource = mapnik.PostGIS(user=str(dbSettings['USER']),password=str(dbSettings['PASSWORD']),
                                    dbname=str(dbSettings['NAME']),table='tms_basemap', srid=4326,
                                    geometry_field="geometry", geometry_table='tms_basemap',
                                    port=5433)
        
        
        baseLayer = mapnik.Layer(str("baseLayer"))
        baseLayer.datasource = datasource
        baseLayer.styles.append(str("baseLayerStyle"))
        
        rule = mapnik.Rule()
        rule.symbols.append(
            mapnik.PolygonSymbolizer(mapnik.Color(str("#b5d19c"))))
        rule.symbols.append(
            mapnik.LineSymbolizer(mapnik.Color(str("#404040")), 0.2))
        style = mapnik.Style()
        style.rules.append(rule)
        
        map.append_style(str("baseLayerStyle"), style) ####
        map.layers.append(baseLayer)
        
        geometry_field = \
            utils.calc_geometry_field(shapefile.geom_type)

        query = '(SELECT ' + geometry_field \
                + ' FROM "shared_feature" WHERE' \
                + ' shapefile_id = ' + str(shapefile.id) + ') as geom'
        
        print query
        print dbSettings['USER'],dbSettings['PASSWORD'],dbSettings['NAME'],query,geometry_field
        datasource = \
            mapnik.PostGIS(user=dbSettings['USER'],
                            password=dbSettings['PASSWORD'],
                            dbname=dbSettings['NAME'],
                            port=dbSettings['PORT'],
                            srid=4326,
                            table=query,
                            geometry_field=geometry_field,
                            geometry_table='shared_feature',
                            )
            
        featureLayer = mapnik.Layer(str("featureLayer"))
        featureLayer.datasource = datasource
        featureLayer.styles.append(str("featureLayerStyle"))
        
        rule = mapnik.Rule()
        
        if shapefile.geom_type in ["Point", "MultiPoint"]:
            rule.symbols.append(mapnik.PointSymbolizer())
        elif shapefile.geom_type in ["LineString", "MultiLineString"]:
            rule.symbols.append(
                mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5))
        elif shapefile.geom_type in ["Polygon", "MultiPolygon"]:
            rule.symbols.append(
                mapnik.PolygonSymbolizer(mapnik.Color(str("#f7edee"))))
            rule.symbols.append(
                mapnik.LineSymbolizer(mapnik.Color(str("#000000")), 0.5))
                
        style = mapnik.Style()
        style.rules.append(rule)    

        map.append_style(str("featureLayerStyle"), style)
        map.layers.append(featureLayer)    
        
        map.zoom_to_box(mapnik.Box2d(minLong, minLat, maxLong, maxLat))
        image = mapnik.Image(TILE_WIDTH, TILE_HEIGHT)
        mapnik.render(map, image)
        imageData = image.tostring(str('png'))
        print imageData
        return HttpResponse(imageData, content_type="image/png")
        
    except:
        traceback.print_exc()
        return HttpResponse("Error")
Esempio n. 15
0
def tile(request, version, shapefile_id, zoom, x, y):
    try:
        if version != "1.0":
            raise Http404
        try:
            shapefile = Shapefile.objects.get(id=shapefile_id)
        except Shapefile.DoesNotExist:
            raise Http404

        zoom = int(zoom)
        x = int(x)
        y = int(y)
        if zoom < 0 or zoom > MAX_ZOOM_LEVEL:
            raise Http404
# Convert the supplied x and y parameters into the minimum and maximum latitude and longitude values covered by the tile. This requires us to use the _unitsPerPixel() function defined earlier to calculate the amount of the Earth's surface covered by the tile for the current zoom level
    	xExtent = _unitsPerPixel(zoom) * TILE_WIDTH
    	yExtent = _unitsPerPixel(zoom) * TILE_HEIGHT
    	minLong = x * xExtent - 180.0
    	minLat = y * yExtent - 90.0
    	maxLong = minLong + xExtent
    	maxLat = minLat + yExtent

	if (minLong < -180 or maxLong > 180 or
	    minLat < -90 or maxLat > 90):
            raise Http404
# Create mapnik.Map object
        map = mapnik2.Map(TILE_WIDTH, TILE_HEIGHT,
                        "+proj=longlat +datum=WGS84")
        map.background = mapnik2.Color("#8aa3ec")

# Define the layer which draws the base map by setting up a mapnik.PostGIS datasource for the layer
        dbSettings = settings.DATABASES['default']
        datasource = \
            mapnik2.PostGIS(user=dbSettings['USER'],
                           password=dbSettings['PASSWORD'],
                           dbname=dbSettings['NAME'],
                           table='tms_basemap',
                           srid=4326,
                           geometry_field="geometry",
                           geometry_table='tms_basemap')
# Create the baselayer itself   
        baseLayer = mapnik2.Layer("baseLayer")
        baseLayer.datasource = datasource
        baseLayer.styles.append("baseLayerStyle")
# Set up the layer's style. In this case, we'll use a single rule with two symbolizers: a PolygonSymbolizer which draws the interior of the base map's polygons, and a LineSymbolizer to draw the polygon outlines


        #labelStyle = mapnik2.Style()
        rule = mapnik2.Rule()
        #symbol = mapnik2.TextSymbolizer(mapnik2.Expression("[name]"),"DejaVu Sans Book", 12, mapnik2.Color("#000000"))
        #rule.symbols.append(symbol)
        #labelStyle.rules.append(rule)



       # rule = mapnik2.Rule()
        rule.symbols.append(
            mapnik2.PolygonSymbolizer(mapnik2.Color("#f0e9e6")))
        rule.symbols.append(
            mapnik2.LineSymbolizer(mapnik2.Color("#807878"), 0.2))
              
        
        
        style = mapnik2.Style()
        style.rules.append(rule)
# Add the base layer and its style to the map
        map.append_style("baseLayerStyle", style)
        map.layers.append(baseLayer)
# Add another layer to draw the shapefile's features onto the map.
# Once again, set up a mapnik.PostGIS datasource for the new layer
        geometryField = utils.calc_geometry_field(shapefile.geom_type)
        #print geometryField
        


        if geometryField=='geom_point':
            query = '(select geom_point from shared_feature where shapefile_id=' + str(shapefile.id) + ') as geom'
        else:
            query = '(select ' + geometryField \
              + ' from "shared_feature" where' \
              + ' shapefile_id=' + str(shapefile.id) + ') as geom'
              
        
        
        print query
                
        datasource = \
            mapnik2.PostGIS(user=dbSettings['USER'],
                            password=dbSettings['PASSWORD'],
                            dbname=dbSettings['NAME'],
                            table=query,
                            srid=4326,
                            geometry_table='shared_feature',
                            geometry_field=geometryField)
        print datasource    
# Create the new layer itself
    	featureLayer = mapnik2.Layer("featureLayer")
    	featureLayer.datasource = datasource
    	featureLayer.styles.append("featureLayerStyle")
# Define the styles used by the feature layer
    	rule = mapnik2.Rule()
    
    	if shapefile.geom_type in ["Point", "MultiPoint"]:
            rule.symbols.append(mapnik2.PointSymbolizer())
    	elif shapefile.geom_type in ["LineString", "MultiLineString"]:
            rule.symbols.append(
                 mapnik2.LineSymbolizer(mapnik2.Color("#404040"), 0.5))
        elif shapefile.geom_type in ["Polygon", "MultiPolygon"]:
            rule.symbols.append(
                mapnik2.PolygonSymbolizer(mapnik2.Color("#f7edee")))
            rule.symbols.append(
                mapnik2.LineSymbolizer(mapnik2.Color("#000000"), 0.5))
        style = mapnik2.Style()
        style.rules.append(rule)
# Add new feature layer to the map
        map.append_style("featureLayerStyle", style)
        map.layers.append(featureLayer)
# Rendering the map tile. Create a mapnik.Image object, convert it into raw image data in PNG format, and return that data back to the caller using an HttpResponse object
        map.zoom_to_box(mapnik2.Box2d(minLong, minLat,
                                     maxLong, maxLat))
        image = mapnik2.Image(TILE_WIDTH, TILE_HEIGHT)
        mapnik2.render(map, image)
        imageData = image.tostring('png')
   
        return HttpResponse(imageData, mimetype="image/png")

# Error-catching 
    except:
        traceback.print_exc()
        return HttpResponse("Error")
Esempio n. 16
0
def import_data(shapefile):

    # Extract the uploaded shapefile.

    fd, fname = tempfile.mkstemp(suffix=".zip")
    os.close(fd)

    f = open(fname, "wb")
    for chunk in shapefile.chunks():
        f.write(chunk)
    f.close()

    if not zipfile.is_zipfile(fname):
        os.remove(fname)
        return "Not a valid zip archive."

    zip = zipfile.ZipFile(fname)

    required_suffixes = [".shp", ".shx", ".dbf", ".prj"]
    has_suffix = {}
    for suffix in required_suffixes:
        has_suffix[suffix] = False

    for info in zip.infolist():
        suffix = os.path.splitext(info.filename)[1].lower()
        if suffix in required_suffixes:
            has_suffix[suffix] = True

    for suffix in required_suffixes:
        if not has_suffix[suffix]:
            zip.close()
            os.remove(fname)
            return "Archive missing required " + suffix + " file."

    shapefile_name = None
    dir_name = tempfile.mkdtemp()
    for info in zip.infolist():
        if info.filename.endswith(".shp"):
            shapefile_name = info.filename

        dst_file = os.path.join(dir_name, info.filename)
        f = open(dst_file, "wb")
        f.write(zip.read(info.filename))
        f.close()
    zip.close()

    # Open the shapefile.

    try:
        datasource = ogr.Open(os.path.join(dir_name, shapefile_name))
        layer = datasource.GetLayer(0)
        shapefile_ok = True
    except:
        traceback.print_exc()
        shapefile_ok = False

    if not shapefile_ok:
        os.remove(fname)
        shutil.rmtree(dir_name)
        return "Not a valid shapefile."

    # Save Shapefile object to database.

    src_spatial_ref = layer.GetSpatialRef()
    geom_type = layer.GetLayerDefn().GetGeomType()
    geom_name = ogr.GeometryTypeToName(geom_type)
    shapefile = Shapefile(filename=shapefile_name,
                          srs_wkt=src_spatial_ref.ExportToWkt(),
                          geom_type=geom_name)
    shapefile.save()

    # Define the shapefile's attributes.

    attributes = []
    layer_def = layer.GetLayerDefn()
    for i in range(layer_def.GetFieldCount()):
        field_def = layer_def.GetFieldDefn(i)
        attr = Attribute(shapefile=shapefile,
                         name=field_def.GetName(),
                         type=field_def.GetType(),
                         width=field_def.GetWidth(),
                         precision=field_def.GetPrecision())
        attr.save()
        attributes.append(attr)

    # Save the Shapefile's features and attributes to disk.

    dst_spatial_ref = osr.SpatialReference()
    dst_spatial_ref.ImportFromEPSG(4326)

    coord_transform = osr.CoordinateTransformation(src_spatial_ref,
                                                   dst_spatial_ref)

    for i in range(layer.GetFeatureCount()):
        src_feature = layer.GetFeature(i)
        src_geometry = src_feature.GetGeometryRef()
        src_geometry.Transform(coord_transform)
        geometry = GEOSGeometry(src_geometry.ExportToWkt())
        geometry = utils.wrap_geos_geometry(geometry)

        geom_field = utils.calc_geometry_field(geom_name)

        fields = {}
        fields['shapefile'] = shapefile
        fields[geom_field] = geometry

        feature = Feature(**fields)
        feature.save()

        for attr in attributes:
            success, result = utils.get_ogr_feature_attribute(
                attr, src_feature)
            if not success:
                os.remove(fname)
                shutil.rmtree(dir_name)
                shapefile.delete()
                return result

            attr_value = AttributeValue(feature=feature,
                                        attribute=attr,
                                        value=result)
            attr_value.save()

    os.remove(fname)
    shutil.rmtree(dir_name)
    return None
def import_data(shapefile):

    # Extract the uploaded shapefile.

    fd,fname = tempfile.mkstemp(suffix=".zip")
    os.close(fd)

    f = open(fname, "wb")
    for chunk in shapefile.chunks():
        f.write(chunk)
    f.close()

    if not zipfile.is_zipfile(fname):
        os.remove(fname)
        return "Not a valid zip archive."

    zip = zipfile.ZipFile(fname)

    required_suffixes = [".shp", ".shx", ".dbf", ".prj"]
    has_suffix = {}
    for suffix in required_suffixes:
        has_suffix[suffix] = False

    for info in zip.infolist():
        suffix = os.path.splitext(info.filename)[1].lower()
        if suffix in required_suffixes:
            has_suffix[suffix] = True

    for suffix in required_suffixes:
        if not has_suffix[suffix]:
            zip.close()
            os.remove(fname)
            return "Archive missing required " + suffix + " file."

    shapefile_name = None
    dir_name = tempfile.mkdtemp()
    for info in zip.infolist():
        if info.filename.endswith(".shp"):
            shapefile_name = info.filename

        dst_file = os.path.join(dir_name, info.filename)
        f = open(dst_file, "wb")
        f.write(zip.read(info.filename))
        f.close()
    zip.close()

    # Open the shapefile.

    try:
        datasource = ogr.Open(os.path.join(dir_name, shapefile_name))
        layer      = datasource.GetLayer(0)
        shapefile_ok = True
    except:
        traceback.print_exc()
        shapefile_ok = False

    if not shapefile_ok:
        os.remove(fname)
        shutil.rmtree(dir_name)
        return "Not a valid shapefile."

    # Save Shapefile object to database.

    src_spatial_ref = layer.GetSpatialRef()
    geom_type = layer.GetLayerDefn().GetGeomType()
    geom_name = ogr.GeometryTypeToName(geom_type)
    shapefile = Shapefile(filename=shapefile_name,
                          srs_wkt=src_spatial_ref.ExportToWkt(),
                          geom_type=geom_name)
    shapefile.save()

    # Define the shapefile's attributes.

    attributes = []
    layer_def = layer.GetLayerDefn()
    for i in range(layer_def.GetFieldCount()):
        field_def = layer_def.GetFieldDefn(i)
        attr = Attribute(shapefile=shapefile,
                         name=field_def.GetName(),
                         type=field_def.GetType(),
                         width=field_def.GetWidth(),
                         precision=field_def.GetPrecision())
        attr.save()
        attributes.append(attr)

    # Save the Shapefile's features and attributes to disk.

    dst_spatial_ref = osr.SpatialReference()
    dst_spatial_ref.ImportFromEPSG(4326)

    coord_transform = osr.CoordinateTransformation(
                                      src_spatial_ref,
                                      dst_spatial_ref)

    for i in range(layer.GetFeatureCount()):
        src_feature = layer.GetFeature(i)
        src_geometry = src_feature.GetGeometryRef()
        src_geometry.Transform(coord_transform)
        geometry = GEOSGeometry(src_geometry.ExportToWkt())
        geometry = utils.wrap_geos_geometry(geometry)

        geom_field = utils.calc_geometry_field(geom_name)

        fields = {}
        fields['shapefile'] = shapefile
        fields[geom_field] = geometry

        feature = Feature(**fields)
        feature.save()

        for attr in attributes:
            success,result = utils.get_ogr_feature_attribute(
                                      attr, src_feature)
            if not success:
                os.remove(fname)
                shutil.rmtree(dir_name)
                shapefile.delete()
                return result

            attr_value = AttributeValue(feature=feature,
                                        attribute=attr,
                                        value=result)
            attr_value.save()

    os.remove(fname)
    shutil.rmtree(dir_name)
    return None
Esempio n. 18
0
def tile(request, version, shapefile_id, zoom, x, y):
    try:
        # Parse and check our parameters.

        if version != "1.0":
            raise Http404

        try:
            shapefile = Shapefile.objects.get(id=shapefile_id)
        except Shapefile.DoesNotExist:
            raise Http404

        zoom = int(zoom)
        x    = int(x)
        y    = int(y)

        if zoom < 0 or zoom > MAX_ZOOM_LEVEL:
            raise Http404

        xExtent = _unitsPerPixel(zoom) * TILE_WIDTH
        yExtent = _unitsPerPixel(zoom) * TILE_HEIGHT

        minLong = x * xExtent - 180.0
        minLat  = y * yExtent - 90.0
        maxLong = minLong + xExtent
        maxLat  = minLat  + yExtent

        if (minLong < -180 or maxLong > 180 or
            minLat < -90 or maxLat > 90):
            raise Http404

        # Set up the map.

        map = mapnik.Map(TILE_WIDTH, TILE_HEIGHT,
                         "+proj=longlat +datum=WGS84")
        map.background = mapnik.Color("#7391ad")

        # Define the base layer.

        dbSettings = settings.DATABASES['default']
        datasource = \
            mapnik.PostGIS(user=dbSettings['USER'],
                           password=dbSettings['PASSWORD'],
                           dbname=dbSettings['NAME'],
                           table='tms_basemap',
                           srid=4326,
                           geometry_field="geometry",
                           geometry_table='tms_basemap')

        baseLayer = mapnik.Layer("baseLayer")
        baseLayer.datasource = datasource
        baseLayer.styles.append("baseLayerStyle")

        rule = mapnik.Rule()

        rule.symbols.append(
            mapnik.PolygonSymbolizer(mapnik.Color("#b5d19c")))
        rule.symbols.append(
            mapnik.LineSymbolizer(mapnik.Color("#404040"), 0.2))

        style = mapnik.Style()
        style.rules.append(rule)

        map.append_style("baseLayerStyle", style)
        map.layers.append(baseLayer)

        # Define the feature layer.

        geometry_field = utils.calc_geometry_field(shapefile.geom_type)

        query = '(select ' + geometry_field \
              + ' from "shared_feature" where' \
              + ' shapefile_id=' + str(shapefile.id) + ') as geom'

        datasource = \
            mapnik.PostGIS(user=dbSettings['USER'],
                           password=dbSettings['PASSWORD'],
                           dbname=dbSettings['NAME'],
                           table=query,
                           srid=4326,
                           geometry_field=geometry_field,
                           geometry_table='shared_feature')

        featureLayer = mapnik.Layer("featureLayer")
        featureLayer.datasource = datasource
        featureLayer.styles.append("featureLayerStyle")

        rule = mapnik.Rule()

        if shapefile.geom_type in ["Point", "MultiPoint"]:
            rule.symbols.append(mapnik.PointSymbolizer())
        elif shapefile.geom_type in ["LineString", "MultiLineString"]:
            rule.symbols.append(
                mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5))
        elif shapefile.geom_type in ["Polygon", "MultiPolygon"]:
            rule.symbols.append(
                mapnik.PolygonSymbolizer(mapnik.Color("#f7edee")))
            rule.symbols.append(
                mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5))

        style = mapnik.Style()
        style.rules.append(rule)

        map.append_style("featureLayerStyle", style)
        map.layers.append(featureLayer)

        # Finally, render the map tile.

        map.zoom_to_box(mapnik.Box2d(minLong, minLat,
                                     maxLong, maxLat))
        image = mapnik.Image(TILE_WIDTH, TILE_HEIGHT)
        mapnik.render(map, image)
        imageData = image.tostring('png')

        return HttpResponse(imageData, content_type="image/png")
    except:
        traceback.print_exc()
        return HttpResponse("Error")
Esempio n. 19
0
def edit_feature(request, shapefile_id, feature_id=None, attributevalue=None):
    userid = request.user
    if request.method == "POST" and "delete" in request.POST:
      return HttpResponseRedirect("/editor/delete_feature/" +
                                  shapefile_id+"/"+feature_id)

    try:
      shapefile = Shapefile.objects.get(id=shapefile_id)
    except ShapeFile.DoesNotExist:
      return HttpResponseNotFound()
      
      
    if request.method == "POST" and "attributevalue" in request.POST:
      print attributevalue	    
      return HttpResponseRedirect("/editor/edit_attributevalue/" +
                                  shapefile_id+"/"+attributevalue)

    try:
      shapefile = Shapefile.objects.get(id=shapefile_id)
    except ShapeFile.DoesNotExist:
      return HttpResponseNotFound()
      
      
    if request.method == "POST" and "addattributevalue" in request.POST:
      print feature_id	    
      return HttpResponseRedirect("/editor/add_attributevalue/" +
                                  str(shapefile_id)+"/"+str(feature_id))

    try:
      shapefile = Shapefile.objects.get(id=shapefile_id)
    except ShapeFile.DoesNotExist:
      return HttpResponseNotFound()
      
      
      
# Create a new Feature object if the feature_id is not specified,
# but fail if an invalid feature ID was specified.

    if feature_id == None:
      feature = Feature(shapefile=shapefile)
           
    else:
      try:
        feature = Feature.objects.get(id=feature_id)
        
      except Feature.DoesNotExist:
        return HttpResponseNotFound()

# Store attributes and attributes' values in an array
    attributes = []
    for attr_value in feature.attributevalue_set.all():
      attributes.append([attr_value.attribute.name,
                         attr_value.value,
                         attr_value.id])
    attributes.sort()



   # get all attributes for shapefile
    q = []
    q = Feature.objects.raw('SELECT * from shared_attribute where shapefile_id=%s', [shapefile_id])
    all_attr = []
    for p in q:
        all_attr.append(p.id)
            
  # get only attributes that have values
    q1 = []
    set_attr = []
    q1 = Feature.objects.raw('SELECT * from shared_attributevalue where feature_id=%s', [feature_id])
    for p in q1:
        set_attr.append(p.attribute_id) 	  
  
    attributes1 = []
    attr1 = []
    for n in all_attr:
        	if n not in set_attr:
                  #print n
                  attr = Attribute.objects.get(id=n)
                  attr1.append(attr.name)
                  attr1.append(attr.id)
                  attributes1.append(attr1)
                  attr1=[]
    attributes1.sort()  
    print attributes1
 
    geometry_field = \
            utils.calc_geometry_field(shapefile.geom_type)
    form_class = utils.get_map_form(shapefile)

    if request.method == "GET":
      wkt = getattr(feature, geometry_field)
      form = form_class({'geometry' : wkt})

      return render(request, "edit_feature.html",
                  {'shapefile' : shapefile,
                   'form' : form,
                   'feature': feature_id,
                   'attributes' : attributes,
                   'available': attributes1,
		   'full_name': request.user.username})
      
    elif request.method == "POST":
      form = form_class(request.POST)
      try:
        if form.is_valid():
          wkt = form.cleaned_data['geometry']
          setattr(feature, geometry_field, wkt)
          feature.save()

          return HttpResponseRedirect("/editor/edit_feature/" +
			    str(shapefile_id)+"/"+str(feature.id))
      except ValueError:
        pass

    return render(request, "edit_feature.html",
                  {'shapefile' : shapefile,
                   'form' : form,
                   'feature': feature_id,
                   'attributes' : attributes,
                   'available': attributes1,
		   'full_name': request.user.username})