예제 #1
0
def tile(request, version, shapefile_id, zoom, x, y):
    try:
        # Parse the supplied parameters to see which area of the map to
        # generate.la
        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)

        # geometryField = utils.calcGeometryField(shapefile.geom_type)
        # geometryType  = utils.calcGeometryFieldType(shapefile.geom_type)

       # try:
            #feature = 4

        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

        # Prepare to display the map.

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

        dbSettings = settings.DATABASES['default']

        # Setup our base layer, which displays the base map.

        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)

        # Setup our feature layer, which displays the features from the
        # shapefile.
        geometry_field = utils.calcGeometryField(shapefile.geom_type)
        query = '(select ' + geometry_field + ' from "shared_feature" where shapefile_id=' + str(shapefile.id) + ') as geom'

        ######print "QUERY: " + query +":" + geometryField+":" + geometryType

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

    #     print "DATA SOURCE IS " + str(datasource)
        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"]:
        style = mapnik.Style()
        # rule = mapnik.Rule()
        # rule.filter = mapnik.Filter("[id] = '2'")
        # symbol = mapnik.PolygonSymbolizer(mapnik.Color("Yellow"))
        # rule.symbols.append(symbol)
        # style.rules.append(rule)


        rule = mapnik.Rule()
        #rule.filter = mapnik.Filter("[id] = '2'")
        rule.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color("#F5F1DE")))   #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)



        


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

        selectedLayer = mapnik.Layer("selectedLayer")
        selectedLayer.datasource = datasource
        selectedLayer.styles.append("selectedLayerStyle")

        style = mapnik.Style()
        rule = mapnik.Rule()
        rule.filter = mapnik.Filter("[id] = " + str(selected))
     
        #rule.filter = mapnik.Filter("[id] = " + "28" + "")
        rule.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color("orange")))
        rule.symbols.append(mapnik.LineSymbolizer(mapnik.Color("orange"), 1))
        style.rules.append(rule)



        map.append_style("selectedLayerStyle", style)
        map.layers.append(selectedLayer)



        # Finally, render the map.
        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()
        raise
예제 #2
0
def export_data(shapefile):
    """ Export the contents of the given shapefile.

        'shapefile' is the Shapefile object to export.

        We create a shapefile which holds the contents of the given shapefile,
        then copy the shapefile into a temporary zip archive.  Upon completion,
        we return a Django HttpResponse object which can be used to send the
        zipped shapefile to the user's web browser.
    """
    # Create an OGR shapefile to hold the data we're exporting.

    dstDir = tempfile.mkdtemp()
    dstFile = str(os.path.join(dstDir, shapefile.filename))

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

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

    coordTransform = osr.CoordinateTransformation(srcSpatialRef,
                                                  dstSpatialRef)

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

    # Define the various fields which will hold our 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)

    # Save the feature geometries and attributes into the shapefile.

    geomField = utils.calcGeometryField(shapefile.geom_type)

    for feature in shapefile.feature_set.all():
        geometry = getattr(feature, geomField)
        geometry = utils.unwrapGEOSGeometry(geometry)
        dstGeometry = ogr.CreateGeometryFromWkt(geometry.wkt)
        dstGeometry.Transform(coordTransform)

        dstFeature = ogr.Feature(layer.GetLayerDefn())
        dstFeature.SetGeometry(dstGeometry)

        for attrValue in feature.attributevalue_set.all():
            utils.setOGRFeatureAttribute(attrValue.attribute,
                                         attrValue.value,
                                         dstFeature,
                                         shapefile.encoding)

        layer.CreateFeature(dstFeature)
        dstFeature.Destroy()

    datasource.Destroy() # Close the file, write everything to disk.

    # Compress the shapefile into a ZIP archive.

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

    shapefileBase = os.path.splitext(dstFile)[0]
    shapefileName = os.path.splitext(shapefile.filename)[0]

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

    zip.close()

    # Clean up our temporary files.

    shutil.rmtree(dstDir)

    # Create an HttpResponse object to send the ZIP file back to the user's web
    # browser.

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