'Convert the Uploaded Shapefile to GeoJSON for display on the map'

@staticmethod
def gis_layer_shapefile_onaccept(form):

    id = form.vars.id
    db = current.db
    tablename = ('gis_layer_shapefile_%s' % id)
    if (tablename in db):
        return
    try:
        from osgeo import ogr
    except ImportError:
        current.response.error = current.T('Python    GDAL    required    for    Shapefile    support!')
    else:
        table = db.gis_layer_shapefile
        ptable = db.gis_projection
        query = ((table.id == id) & (ptable.id == table.projection_id))
        row = db(query).select(table.shape, ptable.epsg, limitby=(0, 1)).first()
        try:
            shapefile = table.shape.retrieve(row.gis_layer_shapefile.shape)
        except:
            current.log.error(('No    Shapefile    found    in    layer    %s!' % id))
            return
        (fileName, fp) = shapefile
        layerName = fileName.rsplit('.', 1)[0]
        cwd = os.getcwd()
        TEMP = os.path.join(cwd, 'temp')
        if (not os.path.exists(TEMP)):
            import tempfile
            TEMP = tempfile.gettempdir()
        tempPath = os.path.join(TEMP, 'Shapefiles')
        if (not os.path.exists(tempPath)):
            try:
                os.mkdir(tempPath)
            except OSError:
                current.log.error(('Unable    to    create    temp    folder    %s!' % tempPath))
                return
        os.chdir(tempPath)
        import zipfile
        myfile = zipfile.ZipFile(fp)
        for ext in ('dbf', 'prj', 'sbn', 'sbx', 'shp', 'shx'):
            fileName = ('%s.%s' % (layerName, ext))
            try:
                file = myfile.read(fileName)
            except KeyError:
                current.log.error(("%s.zip    doesn't    contain    a    file    %s" % (layerName, fileName)))
            else:
                f = open(fileName, 'wb')
                f.write(file)
                f.close()
        myfile.close()
        fp.close()
        projection = row['gis_projection.epsg']
        if (projection != 4326):
            reproject = True
            from osgeo import osr
            inSpatialRef = osr.SpatialReference()
            inSpatialRef.ImportFromEPSG(projection)
            outSpatialRef = osr.SpatialReference()
            outSpatialRef.ImportFromEPSG(4326)
            coordTransform = osr.CoordinateTransformation(inSpatialRef, outSpatialRef)
        else:
            reproject = False
        from dateutil import parser
        parse_date = parser.parse
        shapefile = ('%s.shp' % layerName)
        ds = ogr.Open(shapefile)
        if (ds is None):
            current.response.error = (current.T("Couldn't    open    %s!") % shapefile)
            os.chdir(cwd)
            return
        lyr = ds.GetLayerByName(layerName)
        lyr.ResetReading()
        spatialdb = current.deployment_settings.get_gis_spatialdb()
        geom_type = lyr.GetGeomType()
        wkbPoint = ogr.wkbPoint
        OFTInteger = ogr.OFTInteger
        OFTReal = ogr.OFTReal
        OFTDate = ogr.OFTDate
        OFTDateTime = ogr.OFTDateTime
        OFTTime = ogr.OFTTime
        lyr_defn = lyr.GetLayerDefn()
        nFields = lyr_defn.GetFieldCount()
        GetFieldDefn = lyr_defn.GetFieldDefn
        fields = []
        append = fields.append
        for i in range(nFields):
            field_defn = GetFieldDefn(i)
            fname = field_defn.GetName()
            if (fname.lower() == 'id'):
                fname = 'id_orig'
            elif (fname.lower() == 'lat'):
                fname = 'lat_orig'
            elif (fname.lower() == 'lon'):
                fname = 'lon_orig'
            else:
                try:
                    db.check_reserved_keyword(fname)
                except SyntaxError as e:
                    fname = ('%s_orig' % fname)
            ftype = field_defn.GetType()
            if (ftype == OFTInteger):
                ftype = 'integer'
            elif (ftype == OFTReal):
                ftype = 'double'
            elif (ftype == OFTDate):
                ftype = 'date'
            elif (ftype == OFTDateTime):
                ftype = 'datetime'
            elif (ftype == OFTTime):
                ftype = 'time'
            else:
                ftype = 'string'
            append((fname, ftype))
        features = []
        append = features.append
        for feature in lyr:
            f = {}
            for i in range(nFields):
                fname = fields[i][0]
                ftype = fields[i][1]
                value = feature.GetField(i)
                if (ftype in ('date', 'datetime')):
                    f[fname] = parse_date(value)
                else:
                    f[fname] = value
            geom = feature.GetGeometryRef()
            if (geom is None):
                lat = lon = wkt = None
            else:
                if reproject:
                    geom.Transform(coordTransform)
                if (geom_type == wkbPoint):
                    lon = geom.GetX()
                    lat = geom.GetY()
                    wkt = ('POINT(%f    %f)' % (lon, lat))
                else:
                    wkt = geom.ExportToWkt()
                    centroid = geom.Centroid()
                    lon = centroid.GetX()
                    lat = centroid.GetY()
            f['lat'] = lat
            f['lon'] = lon
            f['wkt'] = wkt
            if spatialdb:
                f['the_geom'] = wkt
            f['layer_id'] = id
            append(f)
        ds = None
        os.chdir(cwd)
        data = json.dumps(fields)
        db((table.id == id)).update(gis_feature_type=geom_type, data=data)
        Fields = [Field('lat', 'float'), Field('lon', 'float'), Field('wkt', 'text'), Field('layer_id', table)]
        append = Fields.append
        for field in fields:
            append(Field(field[0], field[1]))
        if spatialdb:
            append(Field('the_geom', 'geometry()'))
        db._migrate_enabled = True
        db.define_table(tablename, *Fields)
        dbtable = db[tablename]
        db._migrate_enabled = False
        dbtable.truncate()
        for feature in features:
            dbtable.insert(**feature)
    gis_layer_onaccept(form)
