def update_metadata(document='CURRENT'):
    """
    updates metadata in an arcmap document
        document - (optional) the path to an arcmap document or the keyword 'CURRENT'.
            The default is 'CURRENT'
    """
    #set local variables
    dir = GetInstallInfo("desktop")["InstallDir"]
    translator = dir + "Metadata/Translator/ESRI_ISO2ISO19139.xml"
    mxd = MapDocument(document)
    df = ListDataFrames(mxd)
    temp_path = "C:/temp"
    for layer in ListLayers(mxd, "*", df[0]):
        if not layer.isGroupLayer:
            description_text = ""
            path = temp_path + '/' + layer.datasetName + '.xml'
            print(path)
            ExportMetadata_conversion(layer.dataSource, translator, path)
            dom = parse(path)
            fields = ('abstract', 'purpose', 'credit')
            for field in fields:
                tags = dom.getElementsByTagName(field)
                print(str(len(tags)) + ' | ' + str(tags))
                if len(tags):
                    tag_string = tags[0].getElementsByTagName(
                        'gco:CharacterString')[0].childNodes[0].nodeValue
                    description_text = "{} <br /> <p><strong>{}</strong>: {}</p>".format(
                        description_text, field.capitalize(), tag_string)
                    if field == 'credit':
                        layer.credit = tag_string
            print(description_text)
            layer.description = description_text
Exemplo n.º 2
0
    def infos_dataframe(self, dataframe, dico_dframe):
        u"""
        Gets informations about geography and geometry
        """
        # spatial extent
        extent = dataframe.extent
        dico_dframe[u'Xmin'] = round(extent.XMin, 2)
        dico_dframe[u'Xmax'] = round(extent.XMax, 2)
        dico_dframe[u'Ymin'] = round(extent.YMin, 2)
        dico_dframe[u'Ymax'] = round(extent.YMax, 2)

        # map settings
        dico_dframe[u'mapUnits'] = dataframe.mapUnits

        # SRS
        srs = extent.spatialReference
        dico_dframe[u'srs'] = srs.name
        dico_dframe[u'srs_type'] = srs.type
        if srs.type == u'Projected':
            dico_dframe[u'EPSG'] = srs.PCSCode, srs.PCSName, srs.projectionCode, srs.projectionName
        elif srs.type == u'Geographic':
            dico_dframe[u'EPSG'] = srs.GCSCode, srs.GCSName, srs.datumCode, srs.datumName
        else:
            dico_dframe[u'EPSG'] = (srs.PCSCode, srs.PCSName, srs.projectionCode, srs.projectionName),\
                                   (srs.GCSCode, srs.GCSName, srs.datumCode, srs.datumName)

        # layers
        li_layers = ListLayers(dataframe)
        dico_dframe['layers_count'] = len(li_layers)
        dico_dframe['layers_names'] = [layer.name for layer in li_layers]

        # end of function
        return
Exemplo n.º 3
0
def findAndReplaceOldPaths(mxdList, sdeList, featureDict):

    for mxdItem in mxdList:
        mxd = MapDocument(mxdItem)
        print "\nFor the mxd at " + str(mxdItem)
        print "the layers were:\n"

        # featureDict changes:
        mxdLayers = ListLayers(mxd)

        for mxdLayer in mxdLayers:
            # Might be causing locked data sources to not get changed.
            # If you can't access the mxdLayer source, it might not
            # use the supports method correctly.
            if mxdLayer.supports('dataSource'):
                layerSource = mxdLayer.dataSource
                print str(layerSource)
                if layerSource in featureDict.keys():
                    mxdLayer.replaceDataSource(featureDict[layerSource][0],
                                               featureDict[layerSource][1],
                                               featureDict[layerSource][2])
                else:
                    pass
            else:
                pass

        # sdeList changes:
        for sdeItem in sdeList:
            mxd.findAndReplaceWorkspacePaths(sdeItem[0], sdeItem[1])

        print "\nThe new layers are:\n"

        mxdLayers = ListLayers(mxd)

        for mxdLayer in mxdLayers:
            if mxdLayer.supports('dataSource'):
                layerSource = mxdLayer.dataSource
                print str(layerSource)
            else:
                pass

        # Make the changes permanent.
        print "\nSaving mxd...\n"
        mxd.save()

        del mxd
def generate_isochrones(locations, break_value):
    """Create walk shed polygons using the OpenStreetMap network from
    the input locations to the distance of the input break value
    """

    # Create and configure a service area layer, these have the ability
    # generate isochrones
    network_dataset = OSM_PED_ND
    sa_name = 'service_area'
    impedance_attribute = ATTRIBUTE_LEN
    sa_layer = MakeServiceAreaLayer(
        network_dataset, sa_name, impedance_attribute, 'TRAVEL_TO',
        restriction_attribute_name=ATTRIBUTE_PED).getOutput(0)

    # Within the service area layer there are several sub-layers where
    # things are stored such as facilities, polygons, and barriers.
    sa_classes = GetNAClassNames(sa_layer)

    # GetNAClassNames returns a dictionary in which the values are
    # strings that are the names of each class, to get their
    # corresponding layer objects the ListLayers method must be used
    facilities_str = sa_classes['Facilities']
    isochrones_lyr = ListLayers(sa_layer, sa_classes['SAPolygons'])[0]

    solver_props = GetSolverProperties(sa_layer)
    solver_props.defaultBreaks = break_value

    # Service area locations must be stored in the facilities sublayer
    clear_other_stops = 'CLEAR'
    exclude_for_snapping = 'EXCLUDE'
    AddLocations(sa_layer, facilities_str, locations,
                 append=clear_other_stops,
                 exclude_restricted_elements=exclude_for_snapping)

    # Generate the isochrones for this batch of stops, the output will
    # automatically go to the 'sa_isochrones' variable
    Solve(sa_layer)

    i_fields = ['SHAPE@', ID_FIELD, DIST_FIELD]
    i_cursor = InsertCursor(ISOCHRONES, i_fields)

    s_fields = ['SHAPE@', UNIQUE_FIELD]
    with SearchCursor(isochrones_lyr, s_fields) as cursor:
        for geom, output_name in cursor:
            iso_attributes = re.split('\s:\s0\s-\s', output_name)
            stop_id = int(iso_attributes[0])
            break_value = int(iso_attributes[1])

            i_cursor.insertRow((geom, stop_id, break_value))

    del i_cursor
Exemplo n.º 5
0
Created on 2014-08-14
@author: Dirk
updated 2014-09-04 by Dirk
'''

from arcpy import RefreshTOC, RefreshActiveView
from arcpy.mapping import MapDocument, ListDataFrames, ListLayers, RemoveLayer
import os

#mapDocName = r'\\gisdata\ArcGIS\GISdata\MXD\2014090401_CCL_TESTing.mxd'
mapDocName = r'C:\GIS\MXD\2014090401_CCL_TESTing.mxd'  # Try local file copy instead.

mxd = MapDocument(mapDocName)
df = ListDataFrames(mxd)[0]

layers = ListLayers(mxd, "K*",
                    df)  # Use K* to include the KDOR/Tax_Units group layer.

print layers

for layer in layers:
    if hasattr(layer, 'visible'):
        layer.visible = False
    else:
        pass

del layers

layers = ListLayers(mxd, "B*", df)  # Use B* to include the background layer.

print layers
Exemplo n.º 6
0
    def __init__(self, lyr_path, dico_lyr, tipo, txt=''):
        u""" Uses OGR functions to extract basic informations about
        geographic vector file (handles shapefile or MapInfo tables)
        and store into dictionaries.

        lyr_path = path to the LYR file
        dico_lyr = dictionary for global informations
        tipo = format
        text = dictionary of text in the selected language

        see: http://resources.arcgis.com/fr/help/main/10.2/index.html#//00s300000008000000
        """
        # changing working directory to layer folder
        chdir(path.dirname(lyr_path))

        # raising arcpy specific exceptions
        self.alert = 0

        # opening LYR
        try:
            layer_obj = Layer(lyr_path)
        except:
            logging.error("Unable to open this file: ", lyr_path)
            return None

        # ------------ Basics ----------------
        dico_lyr[u'name'] = layer_obj.name
        dico_lyr[u'description'] = layer_obj.description
        dico_lyr[u'folder'] = path.dirname(lyr_path)
        # by default let's start considering there is only one layer
        dico_lyr[u'layers_count'] = 1
        dico_lyr['broken'] = layer_obj.isBroken

        # ------------ LYR type ----------------
        if layer_obj.isFeatureLayer:
            dico_lyr[u'type'] = txt.get('lyr_featL')
            self.infos_geos(layer_obj, dico_lyr)
            self.infos_basics(layer_obj, dico_lyr)
            # features
            # dico_lyr[u'num_obj'] = int(obj_count(lyr_path).getOutput(0))
            # fields
            dico_fields = OrderedDict()
            if layer_obj.isBroken:
                self.erratum(dico_lyr, lyr_path, u'err_corrupt')
                self.alert = self.alert + 1
                return None
            else:
                pass

            try:
                self.infos_fields(layer_obj, dico_lyr, dico_fields)
                dico_lyr[u'fields'] = dico_fields
            except RuntimeError:
                self.erratum(dico_lyr, lyr_path, u'err_corrupt')
                self.alert = self.alert + 1
                return None

            # count features
            with SearchCursor(lyr_path, [dico_fields.keys()[0]]) as cursor:
                rows = {row[0] for row in cursor}

            count = 0
            for row in rows:
                count += 1
            dico_lyr[u'num_obj'] = count

        elif layer_obj.isRasterLayer:
            dico_lyr[u'type'] = txt.get('lyr_rastL')
            self.infos_geos(layer_obj, dico_lyr)
            self.infos_basics(layer_obj, dico_lyr)
        elif layer_obj.isRasterizingLayer:
            dico_lyr[u'type'] = txt.get('lyr_rastzL')
            self.infos_basics(layer_obj, dico_lyr)
        elif layer_obj.isServiceLayer:
            dico_lyr[u'type'] = txt.get('lyr_servL')
            self.infos_basics(layer_obj, dico_lyr)
            if layer_obj.supports("SERVICEPROPERTIES"):
                self.infos_service(layer_obj.serviceProperties, dico_lyr)
            else:
                self.erratum(dico_lyr, lyr_path, u'err_incomp')
                self.alert = self.alert + 1
                return None
        elif layer_obj.isNetworkAnalystLayer:
            dico_lyr['type'] = txt.get('lyr_netwaL')
            self.infos_basics(layer_obj, dico_lyr)
        elif layer_obj.isGroupLayer:
            dico_lyr['type'] = txt.get('lyr_groupL')
            self.infos_basics(layer_obj, dico_lyr)
            # layers inside
            sublayers = ListLayers(layer_obj)
            dico_lyr['layers_count'] = len(sublayers) - 1
            dico_lyr['layers_names'] = [
                sublyr.name for sublyr in sublayers[1:]
            ]
            dico_lyr['layers_sources'] = [
                sublyr.dataSource for sublyr in sublayers[1:]
                if sublyr.supports("DATASOURCE")
            ]
        else:
            self.erratum(dico_lyr, lyr_path, u'err_incomp')
            self.alert = self.alert + 1
            return None

        # scale
        dico_lyr['maxScale'] = layer_obj.maxScale
        dico_lyr['minScale'] = layer_obj.minScale

        # secondary
        dico_lyr['license'] = layer_obj.credits
        dico_lyr['broken'] = layer_obj.isBroken

        # dependencies
        dependencies = [
            f for f in listdir(path.dirname(lyr_path))
            if path.splitext(path.abspath(f))[0] == path.splitext(lyr_path)[0]
            and not path.splitext(path.abspath(f).lower())[1] == ".lyr"
            or path.isfile('%s.xml' % f[:-4])
        ]
        dico_lyr[u'dependencies'] = dependencies

        # cumulated size
        dependencies.append(lyr_path)
        total_size = sum([path.getsize(f) for f in dependencies])
        dico_lyr[u"total_size"] = self.sizeof(total_size)
        dependencies.pop(-1)

        # global dates
        dico_lyr[u'date_actu'] = strftime('%d/%m/%Y',
                                          localtime(path.getmtime(lyr_path)))
        dico_lyr[u'date_crea'] = strftime('%d/%m/%Y',
                                          localtime(path.getctime(lyr_path)))