Esempio n. 1
0
    def onClick(self):
        try:
            workspace = autoPath()
            mxd = arcpy.mapping.MapDocument("CURRENT")
            ddp = mxd.dataDrivenPages
            dfLst = arcpy.mapping.ListDataFrames(mxd)
            pageName = ddp.pageRow.getValue(ddp.pageNameField.name)

            # Set data frame name to credits field (can change to description field) for use in lyrString.
            for df in dfLst:
                for lyr in arcpy.mapping.ListLayers(mxd, "*", df):
                    if isinstance(
                            lyr, arcpy.mapping.Layer) and not lyr.isGroupLayer:
                        lyr.credits = df.name

            lyr = pythonaddins.GetSelectedTOCLayerOrDataFrame()
            if not isinstance(lyr, arcpy.mapping.Layer) or lyr.isGroupLayer:
                pythonaddins.MessageBox(
                    'Please select one (1) layer (not a group or data frame or multiple layers) in the Table Of Contents',
                    'Layer Selection Error', 0)
            else:
                lyrString = "%s_%s_%s.lyr" % (pageName, lyr.name, lyr.credits)
                arcpy.SaveToLayerFile_management(lyr,
                                                 workspace + "\\" + lyrString,
                                                 "ABSOLUTE")
                pythonaddins.MessageBox(
                    "%s layer saved to:\n\n%s\n\nas:\n\n%s" %
                    (lyr.name, workspace, lyrString), "Layer Saved", 0)
        except Exception as e:
            pythonaddins.MessageBox(e, "Error")
Esempio n. 2
0
    def onClick(self):
        print
        genpolig.enabled = False
        gentopo.enabled = False
        nomdist.value = ''
        nomdist.refresh()

        self.ubi = pythonaddins.OpenDialog(nls().inicio().title, False, "#",
                                           nls().inicio().button, lambda x: x,
                                           "Feature Class")
        self.loc = unicode(self.ubi)
        evalue = os.path.basename(self.ubi).split('.')

        if len(evalue) == 1:

            if '.gdb' in self.loc:
                try:
                    nomdist.value = self.getName()
                    nomdist.refresh()
                    genpolig.enabled = True
                    pythonaddins.MessageBox(nls().succesfull, nls().title)
                except:
                    pythonaddins.MessageBox(nls().inicio().fielderror,
                                            nls().titleError)
                    loaddata.onClick()
            else:
                pythonaddins.MessageBox(nls().inicio().typeerror,
                                        nls().titleError)
                loaddata.onClick()
        else:
            pythonaddins.MessageBox(nls().inicio().typeerror, nls().titleError)
            loaddata.onClick()
Esempio n. 3
0
    def convertCoords(x, y):
        thisMap = arcpy.mapping.MapDocument("CURRENT")
        dataFrame = arcpy.mapping.ListDataFrames(thisMap)[0]
        pageX = x
        pageY = y
        df_page_w = dataFrame.elementWidth
        df_page_h = dataFrame.elementHeight
        df_page_x_min = dataFrame.elementPositionX
        df_page_y_min = dataFrame.elementPositionY
        df_page_x_max = df_page_w + df_page_x_min
        df_page_y_max = df_page_h + df_page_y_min

        df_min_x = dataFrame.extent.XMin
        df_min_y = dataFrame.extent.YMin
        df_max_x = dataFrame.extent.XMax
        df_max_y = dataFrame.extent.YMax
        df_proj_w = dataFrame.extent.width
        df_proj_h = dataFrame.extent.height

        if pageX < df_page_x_min or pageX > df_page_x_max:
            pythonaddins.MessageBox(
                'X coordinates are not within map portion of the page.',
                "Out of Bounds")
            return 0, 0
        if pageY < df_page_y_min or pageY > df_page_y_max:
            pythonaddins.MessageBox(
                'Y coordinates are not within map portion of the page.',
                "Out of Bounds")
            return 0, 0

        scale = dataFrame.scale / 39.3701
        map_x = df_min_x + ((pageX - df_page_x_min) * scale)
        map_y = df_min_y + ((pageY - df_page_y_min) * scale)

        return map_x, map_y
Esempio n. 4
0
def convertCoords(x,y):
        thisMap = arcpy.mapping.MapDocument("CURRENT")
        dataFrame = arcpy.mapping.ListDataFrames(thisMap)[0]
        pageX = x
        pageY = y

        #get the data frame dimensions in page units
        df_page_w = dataFrame.elementWidth
        df_page_h = dataFrame.elementHeight
        df_page_x_min = dataFrame.elementPositionX
        df_page_y_min = dataFrame.elementPositionY
        df_page_x_max = df_page_w + df_page_x_min
        df_page_y_max = df_page_h + df_page_y_min

        #get the data frame extent in projected coordinates
        df_min_x = dataFrame.extent.XMin
        df_min_y = dataFrame.extent.YMin
        df_max_x = dataFrame.extent.XMax
        df_max_y = dataFrame.extent.YMax
        df_proj_w = dataFrame.extent.width
        df_proj_h = dataFrame.extent.height
        #ensure the coordinates are in the extent of the data frame
        if pageX < df_page_x_min or pageX > df_page_x_max:
            pythonaddins.MessageBox('X coordinate is not within map portion of the page.', "Out of Bounds")
            return 0,0
        if pageY < df_page_y_min or pageY > df_page_y_max:
            pythonaddins.MessageBox('Y coordinate is not within map portion of the page.', "Out of Bounds")
            return 0,0

        #scale the projected coordinates to map units from the lower left of the data frame
        scale = dataFrame.scale/39.3701
        map_x = df_min_x + ((pageX - df_page_x_min)*scale)
        map_y = df_min_y + ((pageY - df_page_y_min)*scale)

        return map_x,map_y
Esempio n. 5
0
 def onClick(self):
     mxd = arcpy.mapping.MapDocument('current')
     df = arcpy.mapping.ListDataFrames(mxd)[0]
     lyr = fc
     desc = arcpy.Describe(lyr)
     Nr_sel = len(desc.FIDSet.split(";"))
     if Nr_sel == 1 and desc.FIDSet == '':
         pythonaddins.MessageBox(
             u'É necessário selecionar 1 trecho de drenagem', 'INFO', 0)
     elif Nr_sel > 1:
         pythonaddins.MessageBox(
             u'É necessário selecionar apenas 1 trecho de drenagem', 'INFO',
             0)
     elif Nr_sel == 1 and desc.FIDSet <> '':
         cobacia_ini = arcpy.da.SearchCursor(lyr, "Pfaf").next()[0]
         cocurso_ini = COC(cobacia_ini)
         lista_cursos = COC_jusante(cobacia_ini)
         arcpy.SelectLayerByAttribute_management(lyr, "CLEAR_SELECTION")
         where_clause = "Pfaf <= '{}'".format(cobacia_ini)
         lista_cocursos = []
         with arcpy.da.SearchCursor(lyr, 'Pfaf', where_clause) as cursor:
             for row in cursor:
                 cobacia = (row[0])
                 if COC(cobacia) in lista_cursos:
                     lista_cocursos.append(COC(cobacia))
         q = query_jusante(lyr, cobacia_ini, lista_cocursos)
         arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION",
                                                 unicode(q))
         df.zoomToSelectedFeatures()
     pass
Esempio n. 6
0
def selectedLayer():
    """ Return the selected layer object, verify that it's point data."""
    layer = None
    if config.selected_layer:
        # our preference is to always use the selected_layer object, which is
        # populated by our combination box.
        layer = config.selected_layer
    else:
        # if no layer is set, default to the current layer in the TOC
        layer = pythonaddins.GetSelectedTOCLayerOrDataFrame()

    desc = arcpy.Describe(layer)

    if layer is None or desc.datasetType not in config.allowed_formats:
        msg = "No layer selected! Please select a point layer from the table of contents."
        title = "No selected layer"
        pythonaddins.MessageBox(msg, title)
    else:
        if desc.shapeType not in config.allowed_types:
            msg = "Selected layer doesn't contain points."
            title = "No points in layer"
            pythonaddins.MessageBox(msg, title)
            layer = None
        # set our default SRID based on the input data layer
        config.sr = desc.spatialReference
    return layer
 def onClick(self):
     env.overwriteOutput = True
     lyr = pythonaddins.GetSelectedTOCLayerOrDataFrame()
     if isinstance(lyr, arcpy.mapping.Layer) and lyr.isRasterLayer:
         noDataBackground = Con(Raster(lyr.name) != 0, lyr.name)
         fileParts = os.path.splitext(lyr.name)
         savePath = '{0}/{1}-noBG{2}'.format(lyr.workspacePath,
                                             fileParts[0], fileParts[1])
         noDataBackground.save(savePath)
         result = arcpy.MakeRasterLayer_management(
             savePath, '{0}-noBG'.format(fileParts[0]))
     elif isinstance(lyr, list):
         for i in range(len(lyr)):
             if lyr[i].isRasterLayer:
                 noDataBackground = Con(
                     Raster(lyr[i].name) != 0, lyr[i].name)
                 fileParts = os.path.splitext(lyr[i].name)
                 savePath = '{0}/{1}-noBG{2}'.format(
                     lyr[i].workspacePath, fileParts[0], fileParts[1])
                 noDataBackground.save(savePath)
                 result = arcpy.MakeRasterLayer_management(
                     savePath, '{0}-noBG'.format(fileParts[0]))
             else:
                 pythonaddins.MessageBox('Please select a raster layer.',
                                         'Error')
     else:
         pythonaddins.MessageBox('Please select a raster layer.', 'Error')
Esempio n. 8
0
 def onClick(self):
     mxd = arcpy.mapping.MapDocument('CURRENT')
     df = arcpy.mapping.ListDataFrames(mxd, "*")
     activeDfName = mxd.activeDataFrame.name
     i = 0
     for d in df:
         if d.name == activeDfName:
             finalDf = arcpy.mapping.ListDataFrames(mxd, "*")[i]
         else:
             i += 1
     lyr = fc
     desc = arcpy.Describe(lyr)
     Nr_sel = len(desc.FIDSet.split(";"))
     if Nr_sel == 1 and desc.FIDSet == '':
         pythonaddins.MessageBox(
             u'É necessário selecionar 1 trecho de drenagem', 'INFO', 0)
     elif Nr_sel > 1:
         pythonaddins.MessageBox(
             u'É necessário selecionar apenas 1 trecho de drenagem', 'INFO',
             0)
     elif Nr_sel == 1 and desc.FIDSet <> '':
         cobacia_ini = arcpy.da.SearchCursor(lyr, "Pfaf").next()[0]
         cocurso_ini = COC(cobacia_ini)
         NPfaf = "Pfaf"
         Ncocurso = "cocurso"
         arcpy.SelectLayerByAttribute_management(lyr, "CLEAR_SELECTION")
         query = """{0} >= '{1}' AND {2} LIKE '{3}%' """.format(
             arcpy.AddFieldDelimiters(lyr, NPfaf), cobacia_ini,
             arcpy.AddFieldDelimiters(lyr, Ncocurso), cocurso_ini)
         arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION",
                                                 unicode(query))
         finalDf.zoomToSelectedFeatures()
     pass
Esempio n. 9
0
 def onClick(self):
     folder_path = pythonaddins.OpenDialog('Select Folder', False, r'C:\Program Files (x86)\ArcGIS','Add')
     #Ext = [".shp"]
     Ext = [".tif",".img",".pix",".dat"]
     if folder_path == None:
         pythonaddins.MessageBox("请选择一个文件夹",'消息',0)
         exit
     else:
         shpsList = []
         for root,dirs,files in os.walk(folder_path):
             for file in files:
                 filepath = os.path.join(root,file)
                 if os.path.splitext(filepath)[1] in Ext:
                     shpsList.append(filepath)
         mxd = arcpy.mapping.MapDocument('current')
         df = arcpy.mapping.ListDataFrames(mxd)[0]
         i = 1
         for fc in shpsList:
             layer_name = os.path.splitext(os.path.basename(fc))[0] + str(i)
             print layer_name
             arcpy.MakeRasterLayer_management(fc, layer_name)
             del layer_name
             i = i + 1
             arcpy.RefreshTOC()
         pythonaddins.MessageBox("栅格影像数据加载完成",'消息',0)
Esempio n. 10
0
 def onClick(self):
     ubi = pythonaddins.OpenDialog(nls().ConfigGDB().title, False, "#",
                                   nls().ConfigGDB().namebutton,
                                   lambda x: x, "Geodatabase (GDB)")
     if ubi:
         evalue = os.path.basename(ubi).split(".")
         if len(evalue) >= 2:
             if evalue[-1] == 'gdb':
                 if os.path.exists(self.dirname):
                     pass
                 else:
                     os.mkdir(self.dirname)
                 fl = Conexion().path
                 data = {
                     'conn':
                     ubi,
                     'templates':
                     os.path.join(os.path.dirname(__file__), "templates")
                 }
                 self.createJson(fl, data)
                 self.connection = True
                 pythonaddins.MessageBox(nls().suscefull, nls().title)
             else:
                 pythonaddins.MessageBox(nls().ConfigGDB().error,
                                         nls().titleError)
                 self.onClick()
         else:
             pythonaddins.MessageBox(nls().ConfigGDB().error,
                                     nls().titleError)
             self.onClick()
     else:
         pass
Esempio n. 11
0
 def onClick(self):
     if os.path.exists(Conexion().path):
         if loadCode.load:
             savepath = pythonaddins.SaveDialog(
                 nls().mapGeo().titleDialog,
                 '{}.mxd'.format(loadCode.codhoja), "", lambda x: x,
                 'Map Document(MXD)')
             if savepath:
                 evalue = os.path.basename(savepath).split(".")
                 if len(evalue) >= 2:
                     if evalue[-1] != "mxd":
                         pythonaddins.MessageBox(nls().mapGeo().errorFormat,
                                                 nls().titleError)
                 else:
                     savepath = '{}.mxd'.format(savepath)
                 try:
                     self.runProcess(savepath)
                     pythonaddins.MessageBox(nls().suscefull, nls().title)
                 except Exception as e:
                     pythonaddins.MessageBox(e, nls().titleError)
             else:
                 pass
         else:
             pythonaddins.MessageBox(nls().error, nls().titleError)
     else:
         pythonaddins.MessageBox(nls().failedConn, nls().titleError)
Esempio n. 12
0
def validateandrun(thingtodo, answer, clickedx, clickedy):
    # set active mxd, and layer which is currently selected in the TOC
    mxd = arcpy.mapping.MapDocument("CURRENT")
    lyr = arcpy.mapping.ListLayers(
        mxd, pythonaddins.GetSelectedTOCLayerOrDataFrame())[0]
    try:
        matchcount = len(lyr.getSelectionSet())
    except:
        # error message if a layer and a row within that layer are not both selected
        pythonaddins.MessageBox("select both layer and row", "Error", {0})
    else:
        # check that only one row is selected
        if matchcount == 1:
            # calls a function to to one of: update attribute (1), move the point (2), move view to next point (3),
            # reset to original point location (4), or visualize the current and original location of points (5)
            if thingtodo == 1:  # filling text into grod_eva field
                groddecide(answer)
            elif thingtodo == 2:  # there will be a move with two extra parameters
                movepoint(clickedx, clickedy)
            elif thingtodo == 3:  # button next point
                pantonext()
            elif thingtodo == 4:  # the moved point will be reset to its original location
                resetpoint()
            elif thingtodo == 5:  # filling text into curb field
                curbdecide(answer)
            elif thingtodo == 6:  # filling text into evaluation field
                evaluate(answer)
        else:
            # error message if multiple rows are selected
            pythonaddins.MessageBox("more than one row selected", "Error", {0})
    def onClick(self):
        """Calcul de l'itineraire entre deux stations"""
        gdb = "D:\\ProgSIG\\data\\TD_itinearaire.gdb"
        arcpy.env.workspace = gdb
        mxd = arcpy.mapping.MapDocument("CURRENT")

        # On teste l'existance d'une classe d'entités Stations
        if not arcpy.Exists(FC_ALL_STATIONS):
            pythonaddins.MessageBox(
                u"Les stations doivent exister dans le document !",
                u"Calcul d'itinéraires")
            return -1

        # On compte le nombre d'entités sélectionnés dans la couche
        fl_stations = get_layer(mxd, FL_ALL_STATIONS)
        nb = int(arcpy.GetCount_management(fl_stations)[0])
        if nb != 2:
            # Nombre de stations sélectionnées différent de 2
            pythonaddins.MessageBox(
                u"Nombre de stations sélectionnées : {}\nSélectionnez 2 stations !"
                .format(nb), u"Calcul d'itinéraires")
            return -1

        pythonaddins.MessageBox(
            u"Nombre de stations sélectionnées : 2.\nCalcul de l'itinéraire...",
            u"Calcul d'itinéraires")

        # C'est tout bon : on peu calculer l'itinéraire !
        calcule_itineraire(mxd, fl_stations)
Esempio n. 14
0
        def Check_accurancy_None(fc):
            def add_field(fc, field, Type='TEXT'):
                TYPE = [
                    i.name for i in arcpy.ListFields(fc) if i.name == field
                ]
                if not TYPE:
                    arcpy.AddField_management(fc, field, Type)

            list_fields = [
                "GUSH_NUM", "GUSH_SUFFIX", "PARCEL", "LEGAL_AREA", "PNUMTYPE",
                "TALAR_NUMBER", "TALAR_YEAR", "SYS_DATE", "KEY"
            ]

            add_field(fc, 'KEY', Type='TEXT')
            error = []
            all_good = False
            with arcpy.da.UpdateCursor(fc, list_fields) as cursor:
                for row in cursor:
                    row[-1] = str(row[0]) + '-' + str(row[1]) + '-' + str(
                        row[2])
                    li = [i for i in zip(list_fields, row) if i[1] is None]
                    if len(li) > 0:
                        error.append(li)
                    else:
                        all_good = True
                    cursor.updateRow(row)
            pythonaddins.MessageBox(
                'there is None in layers: {}'.format(error), 'INFO', 0)
            if all_good:
                pythonaddins.MessageBox('all fields seems ok', 'INFO', 0)

            error_list = [['1', "שדה עם ערכים חסרים", str(i)] for i in error]
            if not error_list:
                error_list = [['1', '', '']]

            add_field(fc, "accurancy", 'TEXT')
            x = [row[0] for row in arcpy.da.SearchCursor(fc, ["KEY"])]

            all_good_2 = True
            error_dupli = []
            with arcpy.da.UpdateCursor(fc, ["KEY", "accurancy"]) as cursor:
                for row in cursor:
                    row[1] = x.count(row[0])
                    if row[1] > 1:
                        pythonaddins.MessageBox(
                            'there is parcel thats have more then 1 appearnce: {}'
                            .format(row[0]), 'INFO', 0)
                        error_dupli.append(
                            ['2', 'חלקה המופיעה יותר מפעם אחת',
                             str(row[0])])
                        all_good_2 = False
                    else:
                        cursor.updateRow(row)

            if all_good_2:
                pythonaddins.MessageBox('no duplicate', 'INFO', 1)

            error_list = error_list + error_dupli

            return error_list
Esempio n. 15
0
    def onClick(self):
        global editor
        editor.get_current()

        workspace = getworkspace(geomtype=u'Polygon')

        if workspace[u'data'] is not None:
            for data in workspace[u'data']:
                if data[u'gdb'] == editor.path:
                    # create dummy settings_dict with 'Align to Roads' set to 1
                    temp_settings = {
                        key: value
                        for key, value in settings_dict.items()
                    }
                    temp_settings[u'Align to Roads'] = 1

                    rectifybuildings(layer=data[u'lyr'],
                                     roads=data[u'tline'],
                                     extent=workspace[u'extent'],
                                     settings=temp_settings,
                                     force=True,
                                     editor_object=editor)
                    arcpy.RefreshActiveView()
                elif editor.path is None:
                    # Fire a tool from toolbox if layer isn't in an edit session
                    layer = data[u'lyr']
                    title = u'Warning'
                    message = u'{0} layer is not in edit session\nWould you run a geoprocessing tool?'.format(
                        layer.name)
                    mb_type = 1
                    answer = pythonaddins.MessageBox(message, title, mb_type)
                    if answer == u'OK':
                        relpath = os.path.dirname(__file__)
                        toolbox = os.path.join(relpath, u'scripts', u'toolbox',
                                               u'geometry_tools.pyt')
                        pythonaddins.GPToolDialog(toolbox,
                                                  u'OrthogonalizeBuildings')
        else:
            if editor.path is None:
                # Fire a tool from toolbox if there is no selection in a layer and no edit session
                title = u'Warning'
                message = u'{0}\nWould you run a geoprocessing tool?'.format(
                    workspace[u'message'])
                mb_type = 1
                answer = pythonaddins.MessageBox(message, title, mb_type)
                if answer == u'OK':
                    relpath = os.path.dirname(__file__)
                    toolbox = os.path.join(relpath, u'scripts', u'toolbox',
                                           u'geometry_tools.pyt')
                    pythonaddins.GPToolDialog(toolbox,
                                              u'OrthogonalizeBuildings')
            else:
                title = u'Warning'
                message = u'{0}'.format(workspace[u'message'])
                mb_type = 0
                pythonaddins.MessageBox(message, title, mb_type)
Esempio n. 16
0
 def onProcess(self):
     if os.path.exists(Conexion().path):
         if loadCode.load:
             try:
                 self.function()
                 pythonaddins.MessageBox(nls().suscefull, nls().title)
             except Exception as e:
                 pythonaddins.MessageBox(e, nls().titleError)
         else:
             pythonaddins.MessageBox(nls().error, nls().titleError)
     else:
         pythonaddins.MessageBox(nls().failedConn, nls().titleError)
Esempio n. 17
0
 def onClick(self):
     try:
         lyr_name = layerbox.value
         lyr_path = str(get_lyr_path(lyr_name))
         id_field = idbox.value
         if id_field:
             get_curvy(lyr_path, id_field)
         else:
             pythonaddins.MessageBox("You must select an ID field.",
                                     "Attention!")
     except Exception as e:
         pythonaddins.MessageBox(str(e), 'Warning!')
Esempio n. 18
0
    def onClick(self):
        message1 = "Have you saved a text file report from the Check Fabric tool for the setup fabric?\n\n If yes, click OK and navigate to the location.\n\n If not, click Cancel. Please run the Check Fabric tool by right clicking on the parcel fabric. Next save the report as a text file."
        box1 = pythonaddins.MessageBox(message1, "Find Check Fabric Text File",
                                       1)
        if box1 == 'OK':
            textFile = pythonaddins.OpenDialog("Find Check Fabric Text File")
            #print textFile
            F1 = open(textFile, 'rb')
            parcelId1 = []
            for line in F1:
                if "Parcel with ID =" in line:
                    pID = line[17:-28]
                    parcelId1.append(pID)
            pfl = arcpy.mapping.ListLayers(mxd, "*Parcels")
            for layer in pfl:
                if layer.name == "Tax Parcels":
                    polygons = "FabricInvestigation\\Tax Parcels"
                elif layer.name == "Parcels":
                    polygons = "FabricInvestigation\\Parcels"
                else:
                    # Adding a message box here will cause tool to fail due to
                    # the looping of the layers when it finds layers not
                    # containing the Parcels or Tax Parcels.
                    pass
            for ID in parcelId1:
                if ID == parcelId1[0]:
                    where = '"OBJECTID" =' + str(ID)
                else:
                    where = where + 'OR "OBJECTID" = ' + str(ID)

            arcpy.SelectLayerByAttribute_management(polygons, "NEW_SELECTION",
                                                    where)

            box3 = pythonaddins.MessageBox(
                "Done selecting bad parcels. Click Yes if you would like to save as a feature class. Click No to return to map.",
                "Finished Process", 4)
            if box3 == "Yes":
                newFC = pythonaddins.SaveDialog("Save Bad Parcels")
                if newFC != "Cancel":
                    arcpy.CopyFeatures_management(polygons, newFC)
            else:
                pass
        newPath, newLayer = os.path.split(newFC)
        arcpy.mapping.MoveLayer(
            df,
            arcpy.mapping.ListLayers(mxd, "FabricInvestigation")[0],
            arcpy.mapping.ListLayers(mxd, newLayer)[0], "BEFORE")
        Parcel.checked = False
Esempio n. 19
0
 def onClick(self):
     box = pythonaddins.MessageBox("You are about to look for gaps. This process could take a long time depending on the size of the fabric. Please be patient with the interface until it shows a finished message.", \
                                   "Select Parcel Fabric", 1)
     if box == "OK":
         workspace, PFname = os.path.split(parcelFabric)
         topology = os.path.join(workspace, PFname + "_topology")
         if arcpy.Exists(topology):
             arcpy.Delete_management(topology)
         arcpy.CreateTopology_management(workspace, PFname + "_topology")
         pfl = arcpy.mapping.ListLayers(mxd, "*Parcels")
         for layer in pfl:
             if layer.name == "Tax Parcels":
                 polygons = "FabricInvestigation\\Tax Parcels"
             elif layer.name == "Parcels":
                 polygons = "FabricInvestigation\\Parcels"
             else:
                 # Adding a message box here will cause tool to fail due to
                 # the looping of the layers when it finds layers not
                 # containing the Parcels or Tax Parcels.
                 pass
         arcpy.AddFeatureClassToTopology_management(topology, polygons)
         arcpy.AddFeatureClassToTopology_management(
             topology, "FabricInvestigation\\Lines")
         polygon_fc = os.path.join(workspace, PFname + "_Parcels")
         line_fc = os.path.join(workspace, PFname + "_Lines")
         arcpy.AddRuleToTopology_management(
             topology, "Boundary Must Be Covered By (Area-Line)",
             polygon_fc, "", line_fc)
         arcpy.ValidateTopology_management(topology)
         gdb, fds_name = os.path.split(workspace)
         arcpy.ExportTopologyErrors_management(topology, gdb, "Gaps")
         arcpy.mapping.MoveLayer(
             df,
             arcpy.mapping.ListLayers(mxd, "FabricInvestigation")[0],
             arcpy.mapping.ListLayers(mxd, "Gaps_line")[0], "BEFORE")
         arcpy.mapping.RemoveLayer(
             df,
             arcpy.mapping.ListLayers(mxd, "Gaps_point")[0])
         arcpy.mapping.RemoveLayer(
             df,
             arcpy.mapping.ListLayers(mxd, "Gaps_poly")[0])
         arcpy.mapping.RemoveLayer(
             df,
             arcpy.mapping.ListLayers(mxd, PFname + "_topology")[0])
         box2 = pythonaddins.MessageBox(
             "Finished Processing Gaps. Please proceed.",
             "Finsihed Processing Gaps", 0)
         ParcelLineGaps.checked = False
Esempio n. 20
0
        def topology_basic(final):

            gdb           = os.path.dirname(final)
            memory        = r'in_memory'
            random_name   = str(uuid.uuid4())[::5]
            Diss          = memory + '\\' + 'dissolve'                + random_name
            feat_to_poly  = memory + '\\' + 'Feature_to_poly'         + random_name
            topo_holes    = memory + '\\' + 'Topolgy_Check_holes'     + random_name
            topo_inter    = memory + '\\' + 'Topolgy_Check_intersect' + random_name
            error_polygon = gdb     + '\\' + 'Errors_polygon'          

            deleteErrorCode (error_polygon, ["3"])
            deleteErrorCode (error_polygon, ["4"])

            arcpy.Dissolve_management                 (final,Diss)
            Feature_to_polygon                        (Diss,feat_to_poly)
            Delete_polygons                           (feat_to_poly,Diss,topo_holes)

            count_hole  = count_fc(topo_holes)
            if count_hole == 0:
                print ('all ok, no holes layers Foun')
                pythonaddins.MessageBox('all ok, no holes layers Found','INFO',0)
            else:
                pythonaddins.MessageBox('tool Found: {} holes, check Error layer'.format(str(count_hole)),'INFO',0)

            arcpy.Intersect_analysis([final],topo_inter)

            count_inter  = count_fc(topo_inter)
            if count_inter == 0:
                print ('all ok, no intersect layers found')
                pythonaddins.MessageBox('all ok, no intersect layers found','INFO',0)
            else:
                pythonaddins.MessageBox('tool Found: {} intersects, check Error layer'.format(str(count_inter)),'INFO',0)

            Calc_field_value_error  (topo_holes,error_polygon,"3",ErrorDictionary["3"])
            Calc_field_value_error  (topo_inter,error_polygon,"4",ErrorDictionary["4"])

            del_geom(error_polygon)

            arcpy.Delete_management(Diss)
            arcpy.Delete_management(feat_to_poly)

            list_layers = ['dissolve'+ random_name,'Feature_to_poly'+ random_name,'Dissolve_temp',\
                           'Topolgy_Check_holes'+ random_name,'Topolgy_Check_intersect' + random_name,'_temp','Errors_polygon']
            
            Delete_layers_from_MXD(list_layers)

            return count_hole,count_inter
 def onClick(self):
     #get the inputs (theoretically I'd like to loop though and find parent i,j automatically, but there's a variable # of domains and master regions)
     master_domain = pythonaddins.OpenDialog("Select your Master Domain", False, "", "","","")
     nest = pythonaddins.OpenDialog("Select your next Nested Domain", False, "", "","","")
     #calculate extents and get the lat/lon origin of the nested domain
     desc1 = ap.Describe(master_domain)
     desc2 = ap.Describe(nest)
     ext_master = desc1.extent
     ext_nested = desc2.extent
     if ext_master.contains(ext_nested) == True: #check if it actually fits
         nest_x = ext_nested.XMin
         nest_y = ext_nested.YMin
         x_y = "%s %s"%(nest_x, nest_y)
         #get cell value of MASTER at the point from nest 
         cell_val = float(ap.GetCellValue_management(master_domain, x_y, "")[0])
         #with cell value, find index on numpy array
         my_array = ap.RasterToNumPyArray(master_domain)
         index = numpy.where(my_array == cell_val)
         max_rows = int(ap.GetRasterProperties_management(master_domain, "ROWCOUNT", "")[0])
         print "rows complete"
         def index_to_namelist(sample_index, rows): #using the actual index instead of calculating it based on geographic distance 
             i = int(sample_index[1])+1
             y = int(sample_index[0])
             j = rows - y
             return i, j
         i_temp, j_temp = index_to_namelist(index, max_rows)
         global global_i, global_j
         global_i.append(i_temp)
         global_j.append(j_temp)            
         print "The current nest indexes are: \ni: %r \nj:%r\nKeep on going until all nests are added" %(global_i, global_j)
     else:
         pythonaddins.MessageBox("DOMAIN ERROR: Nested domain is not contained within the Master Domain","DOMAIN ERROR!", 5)
         print "Try again!" #message box should get this, but keeping things consistent
Esempio n. 22
0
    def onEditChange(self, text):
        Results.value = ''
        Results.refresh()
        global query
        query = text
        print(query)

        # Check to see if EAD layers are in mxd.
        mxd = arcpy.mapping.MapDocument("CURRENT")
        df = arcpy.mapping.ListDataFrames(mxd, "")[0]
        layer_list = arcpy.mapping.ListLayers(mxd, "EAD Facilities", df)
        print(layer_list)
        if len(layer_list) == 0:
            print("EAD Facilities not present")
            pythonaddins.MessageBox("'EAD Facilities' layer group must be added to map.", "Layers Present", 0)

            # Open the OpenDialog (add data) and create the objects list for use in Addlayer.
            ead_layer_file = pythonaddins.OpenDialog("Add 'EAD Facilities'",
                                                     "False",
                                                     r"PATH\TO\EAD\LAYERS",
                                                     "Open")
            print(ead_layer_file)
            for layer in ead_layer_file:
                # Create object for layer in list.
                ead_lyr = arcpy.mapping.Layer(layer)
                print(ead_lyr)
                # Add object to mxd.
                arcpy.mapping.AddLayer(df, ead_lyr)
                print("Layer added")

        else:
            print("EAD Facilities is present")
Esempio n. 23
0
 def onClick(self):
     inicio = time.time()
     mxd = arcpy.mapping.MapDocument('current')
     df = arcpy.mapping.ListDataFrames(mxd)[0]
     lyr = fc
     field_name = field
     coluna = field_name + "_Acum"
     dfp = gpd.read_file(lyr.workspacePath + "\\" + lyr.name + ".shp")
     dfp[coluna] = 0
     for index, row in dfp.iterrows():
         cobac = row.Pfaf
         cocur = row.cocurso
         dfp_sel = dfp.loc[operator.and_(dfp.Pfaf >= cobac,
                                         dfp.cocurso.str.startswith(cocur))]
         soma = dfp_sel[field_name].sum()
         dfp.loc[index, coluna] = soma
         del dfp_sel
     output = lyr.workspacePath + "\\" + lyr.name + "_Acum.shp"
     dfp.to_file(driver='ESRI Shapefile', filename=output)
     newlayer = arcpy.mapping.Layer(output)
     arcpy.mapping.AddLayer(df, newlayer, "AUTO_ARRANGE")
     arcpy.RefreshActiveView()
     arcpy.RefreshTOC()
     fim = time.time()
     tempo = fim - inicio
     pythonaddins.MessageBox(
         u'Tempo de execução: ' + "%.2f" % tempo + ' segundos', 'INFO', 0)
     pass
 def onClick(self):
     try:
         target = target_layer.target
     except AttributeError:
         pythonaddins.MessageBox(
             'Select target layer from dropdown and retry.', 'Alert')
     oid = [i.name for i in arcpy.ListFields(target) if i.type == 'OID'][0]
     oidf = arcpy.AddFieldDelimiters(target, oid)
     oids = [i[0] for i in arcpy.da.SearchCursor(target, 'OID@')]
     #if len(oids) % 500 != 0:
     chunks = len(oids) / 500 + 1
     query = ''
     #Iterate through 500 features at a time, maximum returned for each SQL query
     for i in range(chunks):
         subset_oids = oids[i * 500:][:(((i + 1) * 500) - 1)]
         #Only block of query - no "OR" in SQL query
         if chunks == 1:
             subset_query = '{0} IN ({1})'.format(
                 oidf, ','.join(map(str, subset_oids)))
             query += subset_query
             #Copy query to clipboard
             pyperclip.copy(query)
             break
         if i == 0:
             subset_query = '{0} IN ({1})'.format(
                 oidf, ','.join(map(str, subset_oids)))
             query += subset_query
         else:
             subset_query = '\nOR {0} IN ({1})'.format(
                 oidf, ','.join(map(str, subset_oids)))
             query += subset_query
         #Copy query to clipboard
         pyperclip.copy(query)
    def onMouseDownMap(self, x, y, button, shift):
        #Capture clicks in map canvas, create points if Point feature type
        self.x = x
        self.y = y

        try:
            self.shp = target_layer.target
        except NameError:
            pythonaddins.MessageBox(
                'Select target layer from dropdown and retry.', 'Alert')
            pass
        desc = arcpy.Describe(self.shp)
        self.type = desc.shapeType

        #If feature is Polyline or Polygon, save points until doubleclick
        if not self.type == 'Point' and self.doubleclick == False:
            self.doubleclick = True
            self.list_pts = []
            self.list_pts.append([x, y])
        elif not self.type == 'Point' and self.doubleclick == True:
            self.list_pts.append([x, y])
        else:
            with arcpy.da.InsertCursor(self.shp, 'SHAPE@XY') as cursor:
                cursor.insertRow([(x, y)])
            arcpy.RefreshActiveView()
 def onClick(self):
     global raster2
     lyr = pythonaddins.GetSelectedTOCLayerOrDataFrame()
     if isinstance(lyr, arcpy.mapping.Layer) and lyr.isRasterLayer:
         raster2 = lyr
     else:
         pythonaddins.MessageBox('Please select a raster layer.', 'Error')
    def onClick(self):
        try:
            global layer
            global username
            global password
            try:
                checkVariable(username)
                checkVariable(password)
            except NameError:
                raise Exception("Please fill username and password.")
            try:
                checkVariable(layer)
            except NameError:
                raise Exception("Please pick a layer.")

            mxd = arcpy.mapping.MapDocument('current')
            df = arcpy.mapping.ListDataFrames(mxd)[0]
            url = "https://api.linearbench.com/azgiv/extent"
            params = {
                'email': username,
                'projection': df.spatialReference.factoryCode
            }
            r = requests.get(url=url, params=params, verify=False)
            data = r.json()
            print data
            xmin = data['xmin']
            ymin = data['ymin']
            xmax = data['xmax']
            ymax = data['ymax']
            ext = arcpy.Extent(xmin, ymin, xmax, ymax)
            df.extent = ext
        except Exception as e:
            pythonaddins.MessageBox(str(e), "ERROR", 0)
Esempio n. 28
0
def evaluate(layer):
    """
    This function evaluates the actual average displacement velocity.

    Args:
        layer (Layer): a reference to the layer containing the SqueeSAR data.

    Returns:
        ave_vel (float): the average displacement velocity of the selected scatterers.
    """
    # Extract field names from the layer
    fld = ap.ListFields(layer)
    fld_names = [f.name for f in fld]

    # Store all data in a structured array
    sel_data = ap.da.FeatureClassToNumPyArray(layer, fld_names)

    # Calculate average displacement velocity. The displacment velocity is
    # "usually" stored in the u"VEL" field.
    if u"VEL" not in fld_names:
        pa.MessageBox("Couldn't find the field 'VEL' in the data.",
                      "Error",
                      0)
    ave_vel = np.average(sel_data[u"VEL"])
    # TODO: I don't really like using named variable. Is there a way to find out or ask the user?

    return ave_vel
    def onLine(self, line_geometry):
        array = arcpy.Array()
        part = line_geometry.getPart(0)
        for pt in part:
            array.add(pt)
        #array.add(line_geometry.firstPoint)
        polygon = arcpy.PolyLine(array)

        rutaDB = arcpy.env.workspace
        #arcpy.env.scratchWorkspace = rutaFD

        if arcpy.Exists("in_memory/polygons"):
            arcpy.Delete_management("in_memory/polygons")
        arcpy.RefreshActiveView()
        arcpy.CopyFeatures_management(polygon, "in_memory/polygons")
        mxd = arcpy.mapping.MapDocument("CURRENT")
        aes = [
            x for x in arcpy.mapping.ListLayers(mxd) if x.name[0:3] == 'AES'
        ][0]
        poligono = [
            x for x in arcpy.mapping.ListLayers(mxd) if x.name == 'polygons'
        ][0]
        arcpy.SelectLayerByLocation_management(aes, "INTERSECT", poligono, "#",
                                               "NEW_SELECTION")
        suma = sum([x[0] for x in arcpy.da.SearchCursor(aes, ["CANT_EST"])])
        with arcpy.da.UpdateCursor(aes, ["RUTA"]) as cursor:
            for c in cursor:
                c[3] = 1
                cursor.updateRow(c)
        arcpy.RefreshActiveView()
        pythonaddins.MessageBox("Establecimientos Totales: {}".format(suma),
                                "INEI", 0)
def configFilesExist():
    if os.path.exists(layerConfigFile) and os.path.exists(mapConfigFile):
        isEnabled = True
    else:
        isEnabled = False
        pythonaddins.MessageBox('Please Import your Configuration File before using this tool', 'Missing Configuration Files', 0)
    return isEnabled