'Lookup Shapefile Layer polygons once per layer and not per-record
Called by S3REST: S3Resource.export_tree()
@ToDo: Vary simplification level & precision by Zoom level
- store this in the style?'

@staticmethod
def get_shapefile_geojson(resource):

    db = current.db
    tablename = resource.tablename
    table = db[tablename]
    query = resource.get_query()
    fields = []
    fappend = fields.append
    for f in table.fields:
        if (f not in ('layer_id', 'lat', 'lon')):
            fappend(f)
    attributes = {}
    geojsons = {}
    settings = current.deployment_settings
    tolerance = settings.get_gis_simplify_tolerance()
    if settings.get_gis_spatialdb():
        fields.remove('the_geom')
        fields.remove('wkt')
        _fields = [table[f] for f in fields]
        rows = db(query).select(table.the_geom.st_simplify(tolerance).st_asgeojson(precision=4).with_alias('geojson'), *_fields)
        for row in rows:
            _row = row[tablename]
            _id = _row.id
            geojsons[_id] = row.geojson
            _attributes = {}
            for f in fields:
                if (f not in 'id'):
                    _attributes[f] = _row[f]
            attributes[_id] = _attributes
    else:
        _fields = [table[f] for f in fields]
        rows = db(query).select(*_fields)
        simplify = GIS.simplify
        for row in rows:
            geojson = simplify(row.wkt, tolerance=tolerance, output='geojson')
            _id = row.id
            if geojson:
                geojsons[_id] = geojson
            _attributes = {}
            for f in fields:
                if (f not in ('id', 'wkt')):
                    _attributes[f] = row[f]
            attributes[_id] = _attributes
    _attributes = {}
    _attributes[tablename] = attributes
    _geojsons = {}
    _geojsons[tablename] = geojsons
    return dict(attributes=_attributes, geojsons=_geojsons)
