Esempio n. 1
0
def criar_linha_largura_app(linha, largura_app):
    x_1_c = linha.firstPoint.X
    y_1_c = linha.firstPoint.Y
    x_2_c = linha.lastPoint.X
    y_2_c = linha.lastPoint.Y
    pt1_geometry = PointGeometry(linha.firstPoint, projecao_geo)
    pt2_geometry = PointGeometry(linha.lastPoint, projecao_geo)
    circ_poly_1 = pt1_geometry.projectAs(projecao_plana).buffer(largura_app).projectAs(projecao_geo).boundary()
    x_1_nocirc = circ_poly_1.firstPoint.X
    y_1_nocirc = circ_poly_1.firstPoint.Y
    obj_circ = CircVetores(x_1_c,y_1_c)
    raio = obj_circ.eq_circ_achar_raio(x_1_nocirc,y_1_nocirc)
    angulo_rad = obj_circ.retorna_angulo_atraves_ponto(x_2_c,y_2_c)
    x_1_final, y_1_final = obj_circ.retorna_ponto_de_angulo_inverso(angulo_rad, raio)
    del obj_circ

    circ_poly_2 = pt2_geometry.projectAs(projecao_plana).buffer(largura_app).projectAs(projecao_geo).boundary()
    x_2_nocirc = circ_poly_2.firstPoint.X
    y_2_nocirc = circ_poly_2.firstPoint.Y
    obj_circ = CircVetores(x_2_c,y_2_c)
    raio = obj_circ.eq_circ_achar_raio(x_2_nocirc,y_2_nocirc)
    angulo_rad = obj_circ.retorna_angulo_atraves_ponto(x_1_c,y_1_c)
    x_2_final, y_2_final = obj_circ.retorna_ponto_de_angulo_inverso(angulo_rad, raio)
    del obj_circ
    point1_final = Point()
    point1_final.X = x_1_final
    point1_final.Y = y_1_final
    point2_final = Point()
    point2_final.X = x_2_final
    point2_final.Y = y_2_final
    array = Array([point1_final, point2_final])
    linha_app = Polyline(array, projecao_geo)
    del array
    return linha_app
Esempio n. 2
0
 def curse(self):
     try:
         op_status_f = AddFieldDelimiters(self.hqiis, "OPERATIONAL_STATUS_NAME")
         type_f = AddFieldDelimiters(self.hqiis, "RPA_TYPE_CODE")
         with SearchCursor(self.hqiis, ["INSTALLATION_CODE", "SITE_UID", "RPA_UID", "RPA_PREDOMINANT_CURRENT_USE_CAT"],
                           where_clause="{0}<>'{1}' AND {2}<>'{3}'".format(op_status_f, "Closed ", type_f, "L")) as s_cursor:
             for r in s_cursor:
                 if r[2] in self.previous_rpuids:
                     continue
                 fcs = self.__is_applicable(r[3])
                 if not fcs:
                     self.previous_rpuids.append(r[2])
                     continue
                 if not self.__check_exist_in_db(r[2], fcs):
                     self.layer_status.add_status(r[0], r[1], fcs[0], 2)
                     ft = fcs[0]
                     shape = self.__lookup_geometry(r[1])
                     if not shape:
                         gen_point = Point(0, 0, 0)
                         shape = PointGeometry(gen_point)
                         self.log.info(str(r[1]) + " not in 'Site' layer.")
                     need = NewNeed(shape, r[1], r[2], ft, r[0])
                     need.push()
                     del need
                 else:
                     self.layer_status.add_status(r[0], r[1], fcs[0], 1)
                 self.previous_rpuids.append(r[2])
     except Exception as e:
         cache = File("CheckForNeeds", self.previous_rpuids)
         if not cache.save():
             self.log.error("Cache did not work.")
         self.layer_status.write_cache()
         self.log.exception(e.message)
         raise Exit()
     else:
         self.layer_status.post_to_table()
flCounty = GetParameterAsText(4)
strFilePath = GetParameterAsText(5)

# Convert values from text to float
floLatitude = float(strLatitude)
floLongitude = float(strLongitude)

# Make a Point Geometry object.
try:
    ptPointOfInterest = Point(X=floLongitude,
                              Y=floLatitude,
                              Z=None,
                              M=None,
                              ID=0)
    spatial_ref = SpatialReference(4269)
    ptGeometry = PointGeometry(ptPointOfInterest, spatial_ref)
except:
    strErrorMsg = "Error creating Point or PointGeometry objects."
    AddWarning(strErrorMsg)
    SetParameterAsText(6, strErrorMsg)
    sys.exit()

# Open Output File for use
try:
    fhand = open(strFilePath, 'w')
except:
    strErrorMsg = "File did not open"
    AddWarning(strErrorMsg)
    SetParameterAsText(6, strErrorMsg)
    sys.exit()
Esempio n. 4
0
def ponto_oposto(ponto, dict_circ_desc):
    ponto_buffer = ponto.projectAs(projecao_plana).buffer(1).projectAs(projecao_geo)
    for point in dict_circ_desc['linha_largura'].getPart(0):
        pt =  PointGeometry(point, projecao_geo)
        if pt.disjoint(ponto_buffer):
            return pt
Esempio n. 5
0
def OffsetDirectionMatrix2(offsetOptions):
    """Update the accidentDataWithOffsetOutput geometry with data from geocodedFeatures.
    
    Keyword arguments to be included in the options class:
    gdbLocation -- The gdb where the outputWithOffsetLocations feature class resides.
    accidentDataAtIntersections -- A point feature class containing geocoded accident information.
    accidentDataWithOffsetOutput -- A point feature class with the same structure as the 
        geocodedFeatuers AND an "isOffset" row of type "TEXT" with length of at least 5.
    whereClauseInUse -- Whether or not the script will use a where clause. Boolean value.
    roadsFeaturesLocation -- The path to the local roads centerline feature class.
    aliasTable -- The path to the roads alias table for the roads centerline feature class.
    maxDegreesDifference -- The number of degrees that a potentially matching accident
        offset location can be from the direction specified. If this is set to -1, the check
        will be skipped and no matching accident offset locations will be rejected, even if
        they are in the opposite direction from where the accident record says they should
        be. I.e. the accident could be offset to the North when the accident record says that
        it should be South of the intersection when this check is skipped.
    XYFieldList -- The list of fields to use from the copy of the geocoded accidents feature
        class after that copy has had POINT_X and POINT_Y fields added and calculated.
    """
    
    ###########################################################################
    ## Function overview:
    ## For each row in the feature class of accidents that have been geolocated
    ## to an intersection:
    ###########################################################################
    # Make sure that the Status for the point is not 'U' -- Unlocated.
    # Might take care of test for 'U' points before getting to this
    # step in the process, but if not, be sure to test for it here.
    # Create/calculate intersection X & Y field named POINT_X and POINT_Y.
    # Then, calculate those fields.
    # Then, create a buffer.
    # Then, select the On_Road in the roads layer.
    # Then, intersect the buffer with the roads layer to create an offset
    # points layer.
    # Then, split the offset points from potential multipart points to
    # singlepart points.
    ###########################################################################
    # Then, use the "SHAPE@XY" token to access the X & Y of the individual
    # offset points and compare them to the X & Y values in the POINT_X and
    # POINT_Y fields, which hold the values for the related roads' intersection
    # that the accidents were geolocated to.
    # Then, test the intersected points to find the best one for the given
    # direction.
    ###########################################################################
    # Then, append the information for that point into a list.
    # Then, delete the buffer and intersection layer.
    # Repeat for each other row...
    ###########################################################################
    # When all the rows are finished,
    # Append the attribute information for the
    # related accident into each offset point's row.
    # Lastly, write the data for all the offset point rows
    # into the output layer.
    ###########################################################################
    # Maximum angle difference code confirmed to be working. -- 2015-03-18
    # 771/771 manually checked look good (for the information given) using
    # UpdateKdotNameInCenterline(), Where Clause for selection, and
    # Maximum Angle Difference.
    # Locates 771/862 non-'U' points without the modified versions of 
    # ON_ROAD_NAME/AT_ROAD/AT_ROAD_DIRECTION/AT_ROAD_DIST_FEET labeled fields
    # and 803/862 with them. 
    ###########################################################################
    
    AddMessage("The value of the useKDOTFields option is: " + str(offsetOptions.useKDOTFields))
    
    roadsToIntersect = offsetOptions.roadsFeaturesLocation
    roadsAliasTable = offsetOptions.aliasTable
    geocodedFeatures = offsetOptions.accidentDataAtIntersections
    outputWithOffsetLocations = offsetOptions.accidentDataWithOffsetOutput
    whereClauseFlag = offsetOptions.whereClauseInUse
    maximumDegreesDifference = offsetOptions.maxDegreesDifference
    KDOTFieldUse = offsetOptions.useKDOTFields
    
    AddMessage("The value for KDOTFieldUse is: " + str(KDOTFieldUse))
    
    if str(KDOTFieldUse).lower() == 'false':
        featuresWithXYFieldList = offsetOptions.NonKDOTXYFieldList
        AddMessage("Using nonKDOTXYFieldList.")
    else:
        featuresWithXYFieldList = offsetOptions.KDOTXYFieldList
    
    geodatabaseLocation = getGDBLocationFromFC(outputWithOffsetLocations)
    
    env.workspace = geodatabaseLocation
    env.overwriteOutput = True
    geocodedWhereClause = "STATUS <> 'U'"
    featuresWithXY = 'geocodedWithXY'
    geocodedLocXY = r'in_memory\geocodedFeatures_Loc_XY' # Changed this to an in_memory location also.
    
    # Scratch data locations
    intermediateAccidentBuffer = r'in_memory\intermediateAccidentBuffer'
    intermediateAccidentIntersect = r'in_memory\intermediateAccidentIntersect'
    intermediateAccidentIntersectSinglePart = r'in_memory\intermediateAccidentIntersectSinglePart'
    # Added 2016-09-06 after the Wichita Area points started processing. Slowly.
    intermediateRoadsToIntersect = r'in_memory\roadsToIntersect'
    intermediateRoadsAliasTable = r'in_memory\roadsAliasTable'
    
    descSpatialReference = Describe(geocodedFeatures).spatialReference
    
    # Make a feature layer of geocodedFeatures using a where clause to restrict to those points
    # which have been located to an intersection, then add XY to it.
    MakeFeatureLayer_management(geocodedFeatures, featuresWithXY, geocodedWhereClause)
    CopyFeatures_management(featuresWithXY, geocodedLocXY)
    AddXY_management(geocodedLocXY)
    
    roadsAsFeatureLayer = 'ConflatedRoadsFeatureLayer'
    
    # Roads copied to memory.
    CopyFeatures_management(roadsToIntersect, intermediateRoadsToIntersect)
    
    MakeFeatureLayer_management(intermediateRoadsToIntersect, roadsAsFeatureLayer)
    
    # Use Point_X & Point_Y for the geolocated intersection location.
    # Use shape tokens for the x & y of the points which
    # result from intersecting the buffer & road geometries.    
    
    geocodedAccidentsList = list()
    singlePartOffsetAccidentsList = list()
    
    print "The path of the geocodedFeatures used is: " + geocodedFeatures
    
    #AddMessage("The field names used in the search cursor are:")
    #for fieldListItem in featuresWithXYFieldList:
    #    AddMessage(fieldListItem)
    
    accidentsCursor = SearchCursor(geocodedLocXY, featuresWithXYFieldList)
    
    for accidentRow in accidentsCursor:
        geocodedAccidentsList.append(accidentRow)
    
    try:
        del accidentsCursor
    except:
        pass
    
    print 'whereClauseFlag is: ' + str(whereClauseFlag)
    print 'Starting the offset process...'
    
    accCounter = -1
    
    env.outputCoordinateSystem = descSpatialReference
    
    if whereClauseFlag == True:
        
        # Don't need to create a relate or a join.
        # Just need to do a select on the would-be joined/related table
        # to get the SEGIDs, then use those to do a select
        # for the GCIDs the conflation roads.
        
        # Try using table to table here instead of copy features.
        # For some reason, arcpy doesn't like this table when it's in the
        # ar63 FGDBs.
        TableToTable_conversion(roadsAliasTable, 'in_memory', 'roadsAliasTable') # == intermediateRoadsAliasTable
        #CopyFeatures_management(roadsAliasTable, intermediateRoadsAliasTable)
        
        roadsAliasTableView = MakeTableView_management(intermediateRoadsAliasTable, 'roadsAliasTableView')
        
        for geocodedAccident in geocodedAccidentsList:
            accCounter += 1
            print 'Working on geocodedAccident #' + str(accCounter)
            # Create a point here with the x & y from the geocodedAccident,
            # add the coordinate system, OBJECTID, and AccidentID
            # from the geocodedAccident layer.
            # Then, create a buffer with it.
            
            #if geocodedAccident[2] is not None and geocodedAccident[3] is not None:
            tempPoint = Point(geocodedAccident[2], geocodedAccident[3])
            #print "\t " + str(tempPoint.X) + ", " + str(tempPoint.Y)
            tempPointGeometry = PointGeometry(tempPoint, descSpatialReference)
            accidentDistanceOffset = geocodedAccident[7]
            accidentClusterTolerance = 1
            
            
            try:
                #####################
                # Offsetting while using a WhereClause follows:
                #####################
                if accidentDistanceOffset is not None: # In Python it's None, whereas in an ArcGIS table it's <null>
                    
                    accidentDistanceOffset = int(accidentDistanceOffset)
                    
                    if accidentDistanceOffset != 0:
                        
                        Buffer_analysis(tempPointGeometry, intermediateAccidentBuffer, accidentDistanceOffset)
                        
                        firstRoadName = str(geocodedAccident[5])
                        if firstRoadName is not None:
                            firstRoadName = firstRoadName.upper()
                        else:
                            firstRoadName = 'NotAValidRoad'
                        
                        secondRoadName = str(geocodedAccident[8])
                        if secondRoadName is not None:
                            secondRoadName = secondRoadName.upper()
                        else:
                            secondRoadName = 'NotAValidRoad'
                        
                        thirdRoadName = ParseMatchAddr(geocodedAccident[9])
                        if thirdRoadName is not None:
                            thirdRoadName = thirdRoadName.upper()
                        else:
                            thirdRoadName = 'NotAValidRoad'
                        
                        roadNamesList = [firstRoadName, secondRoadName, thirdRoadName]
                        
                        aliasIDsList = getAliasIDs(roadNamesList, roadsAliasTableView)
                        
                        aliasIDsLength = len(aliasIDsList)
                        
                        if aliasIDsLength != 0:
                            aliasIDsString = """("""
                            for x in xrange(aliasIDsLength):
                                if (x != (aliasIDsLength - 1)):
                                    aliasIDsString += """'""" + aliasIDsList[x] + """',"""
                                else:
                                    aliasIDsString += """'""" + aliasIDsList[x] + """')"""
                            
                            streetWhereClause = (""" "RD" = '""" + firstRoadName  + """'""" + """ OR """ +
                                                """ "LABEL" = '""" + firstRoadName + """'""" + """ OR """ +
                                                """ "RD" = '""" + secondRoadName  + """'""" + """ OR """ +
                                                """ "LABEL" = '""" + secondRoadName + """'""" + """ OR """ +
                                                """ "RD" = '""" + thirdRoadName  + """'""" + """ OR """ +
                                                """ "LABEL" = '""" + thirdRoadName + """'""" +
                                                """ OR GCID IN """ + aliasIDsString)
                        else:
                            #Without the aliasIDs.
                            streetWhereClause = (""" "RD" = '""" + firstRoadName  + """'""" + """ OR """ +
                                                """ "LABEL" = '""" + firstRoadName + """'""" + """ OR """ +
                                                """ "RD" = '""" + secondRoadName  + """'""" + """ OR """ +
                                                """ "LABEL" = '""" + secondRoadName + """'""" + """ OR """ +
                                                """ "RD" = '""" + thirdRoadName  + """'""" + """ OR """ +
                                                """ "LABEL" = '""" + thirdRoadName + """'""")
                        
                        
                        SelectLayerByAttribute_management(roadsAsFeatureLayer, "NEW_SELECTION", streetWhereClause)
                        
                        selectionCount = str(int(GetCount_management(roadsAsFeatureLayer).getOutput(0)))
                        
                        if int(selectionCount) != 0:
                            featuresToIntersect = [roadsAsFeatureLayer, intermediateAccidentBuffer]
                            Intersect_analysis(featuresToIntersect, intermediateAccidentIntersect, "ALL", "", "POINT")
                            
                            if  int(str(GetCount_management(intermediateAccidentIntersect))) > 0:
                                MultipartToSinglepart_management(intermediateAccidentIntersect, intermediateAccidentIntersectSinglePart)
                                
                                singlePartsCursor = SearchCursor(intermediateAccidentIntersectSinglePart, ['SHAPE@XY'])
                                for singlePart in singlePartsCursor:
                                    singlePartListItem = [singlePart[0], geocodedAccident[2], geocodedAccident[3], geocodedAccident[4],
                                                               geocodedAccident[6], geocodedAccident[0]]
                                    singlePartOffsetAccidentsList.append(singlePartListItem)
                                
                                try:
                                    del singlePartsCursor
                                except:
                                    pass
                            else:
                                pass
                            try:
                                del intermediateAccidentIntersect
                            except:
                                pass
                        else:
                            pass
                            #print 'Zero road segments selected. Will not attempt to offset.'
                    else:
                        pass
                        #print 'AT_ROAD_DIST_FEET is 0. Will not attempt to offset.
                else:
                    pass
                    #print 'AT_ROAD_DIST_FEET is null. Will not attempt to offset.'
                
            except:
                # Need to log the warnings with details so that I know what's wrong with them.
                print "WARNING:"
                print "An error occurred which prevented the accident point with Acc_Key: " + str(geocodedAccident[4])
                print "from being buffered and/or offset properly."
                errorItem = sys.exc_info()[1]
                errorStatement = str(errorItem.args[0])
                print errorStatement
                
                try:
                    del errorItem
                except:
                    pass
    
    
    elif whereClauseFlag == False:
        for geocodedAccident in geocodedAccidentsList:
            
            # Create a point here with the x & y from the geocodedAccident,
            # add the coordinate system, OBJECTID, and AccidentID
            # from the geocodedAccident layer.
            # Then, create a buffer with it.
            
            #if geocodedAccident[2] is not None and geocodedAccident[3] is not None:
            tempPoint = Point(geocodedAccident[2], geocodedAccident[3])
            #print "\t " + str(tempPoint.X) + ", " + str(tempPoint.Y)
            tempPointGeometry = PointGeometry(tempPoint, descSpatialReference)
            accidentDistanceOffset = geocodedAccident[7]
            ##accidentClusterTolerance = 2
            
            try:
                #####################
                # Offsetting while not using a WhereClause follows:
                #####################
                
                if accidentDistanceOffset is not None:
                    if int(accidentDistanceOffset) != 0:
                        accidentDistanceOffset = int(accidentDistanceOffset)
                        
                        Buffer_analysis(tempPointGeometry, intermediateAccidentBuffer, accidentDistanceOffset)
                        
                        featuresToIntersect = [roadsAsFeatureLayer, intermediateAccidentBuffer]
                        Intersect_analysis(featuresToIntersect, intermediateAccidentIntersect, "ALL", "", "POINT")
                        if  int(str(GetCount_management(intermediateAccidentIntersect))) > 0:
                            MultipartToSinglepart_management(intermediateAccidentIntersect, intermediateAccidentIntersectSinglePart)
                            
                            singlePartsCursor = SearchCursor(intermediateAccidentIntersectSinglePart, ['SHAPE@XY'])
                            for singlePart in singlePartsCursor:
                                singlePartListItem = [singlePart[0], geocodedAccident[2], geocodedAccident[3], geocodedAccident[4],
                                                           geocodedAccident[6], geocodedAccident[0]]
                                singlePartOffsetAccidentsList.append(singlePartListItem)
                            
                            try:
                                del singlePartsCursor
                            except:
                                pass
                            try:
                                del intermediateAccidentIntersect
                            except:
                                pass
                        else:
                            pass
                    else:
                        pass
                        # Need to change this to being offset to the intersection, i.e. no movement, but
                        # considered to be correctly offset all the same.
                        #print 'AT_ROAD_DIST_FEET is 0. Will not attempt to offset.' 
                else:
                    pass
                    #print 'AT_ROAD_DIST_FEET is null. Will not attempt to offset.'
            except:
                print "WARNING:"
                print "An error occurred which prevented the accident point with Acc_Key: " + str(geocodedAccident[4])
                print "from being buffered and/or offset properly."
                errorItem = sys.exc_info()[1]
                errorStatement = str(errorItem.args[0])
                print errorStatement
                
                try:
                    del errorItem
                except:
                    pass
    
    
    else:
        print 'Please set the whereClauseFlag to either (boolean) True or False.'
        #pass
    
    offsetDictionaryByAccidentKey = dict()
    listContainer = list()
    
    # Group the rows by accident_key for further analysis,
    # and add them to the dictionary/list/list data structure.
    
    for singlePartOffsetItem in singlePartOffsetAccidentsList:
        if singlePartOffsetItem[3] in offsetDictionaryByAccidentKey.keys():
            listContainer = offsetDictionaryByAccidentKey[singlePartOffsetItem[3]]
            listContainer.append(singlePartOffsetItem)
            offsetDictionaryByAccidentKey[singlePartOffsetItem[3]] = listContainer
        else:
            listContainer = list()
            listContainer.append(singlePartOffsetItem)
            offsetDictionaryByAccidentKey[singlePartOffsetItem[3]] = listContainer
    
    updateListValues = list()
    
    for accidentKey in offsetDictionaryByAccidentKey.keys():
        # accidentKey will be a unique accident key from the table
        listContainer = offsetDictionaryByAccidentKey[accidentKey]
        updateList = [-1, -1, -1, "False"]
        try:
            # Get the AT_ROAD_KDOT_DIRECTION/AT_ROAD_DIRECTION from the first (0th) entry.
            directionToTest = listContainer[0][4] 
            if directionToTest is not None:
                directionToTest = str(directionToTest).upper()
                updateList = findTheMostInterestingRow(listContainer, directionToTest, maximumDegreesDifference)
                if updateList[0] != -1:
                    updateListValues.append(updateList)
                else:
                    # -1 is not a valid Acc_Key. Slight optimization for the next for loop that uses this list so that
                    # it doesn't have to be re-checked each time through the list for each accident in the table.
                    pass
            else:
                print 'Direction to test is null.'
        except:
            pass
    
    accidentUpdateCursorFields = ['ACCIDENT_KEY', 'Shape@XY', 'isOffset']
    
    accidentUpdateCursor = UpdateCursor(outputWithOffsetLocations, accidentUpdateCursorFields)
    for cursorItem in accidentUpdateCursor:
        for updateListItem in updateListValues:
            if cursorItem[0] == updateListItem[0]:
                if str(cursorItem[2]).upper() == 'TRUE':    # Don't make any changes if true.
                    AddMessage('The accident point with Acc_Key: ' + str(cursorItem[0]) + ' is already offset.')
                else:                                       # Otherwise, offset the point.
                    editableCursorItem = list(cursorItem)
                    #AddMessage('Found a matching cursorItem with an Accident_Key of ' + str(cursorItem[0]) + ".")
                    editableCursorItem[1] = (updateListItem[1], updateListItem[2])
                    editableCursorItem[2] = updateListItem[3]
                    #AddMessage(str(editableCursorItem))
                    accidentUpdateCursor.updateRow(editableCursorItem)
                    
            else:
                pass
Esempio n. 6
0
    field_type = field[1]  # Field type
    # Create all the necessary field for the line feature class
    AddField_management(env.scratchGDB + '/' + OutputLine, field_name,
                        field_type)

# The insert cursor for line feature class
line_ins = da.InsertCursor(env.scratchGDB + '/' + OutputLine,
                           field_names_shapes)

with da.SearchCursor(POK_Table,
                     [X_Start, Y_Start, X_End, Y_End, POK_RID]) as search:
    for t_row in search:  # Iterate over all available POK segment
        route = t_row[4]  # The POK route ID

        # Start Point and End Point in WGS 1984 projection system
        start_point = PointGeometry(Point(t_row[0],
                                          t_row[1])).projectAs('4326')
        end_point = PointGeometry(Point(t_row[2], t_row[3])).projectAs('4326')

        # Start Point and End Point in same projection as the Network Feature Class
        start_point = start_point.projectAs(Network_SpatRef)
        end_point = end_point.projectAs(Network_SpatRef)

        route_found = False  # Variable for determining if the requested routes exist in the Network FC

        # Iterate over all available row in Network Feature Class
        with da.SearchCursor(Network,
                             'SHAPE@',
                             where_clause="{0}='{1}'".format(
                                 NetworkRID, route)) as search_cur:
            for s_row in search_cur:
                route_found = True  # If the route exist
Esempio n. 7
0
def calc_coordinates(fc, updateOnlyBlank):

    ct = CoordConvertor.CoordTranslator()

    AddMessage("Calculating coordinates. For large datasets, this process can a while.")

    #get default address point object
    a = getFCObject(fc)

    #set field names based on object
    xField = a.X
    yField = a.Y
    NG = a.USNGRID

    #establish workspace
    path = dirname(fc)

    if '.gdb' in path:
        place = path.find('.gdb') + 4
    else:
        if '.sde' in path:
            place = path.find('.sde') + 4
        else:
            place = len(path) - 1

    workspace = path[:place]

    AddMessage(workspace)

    #Start an edit session
    edit = Editor(workspace)

    # Edit session is started without an undo/redo stack for versioned data
    #  (for second argument, use False for unversioned data)
    edit.startEditing(False, True)

    # Start an edit operation
    edit.startOperation()

    fl = "fl"
    # If necessary, only update blank records
    if updateOnlyBlank == "true":
        wc = NG + " IS NULL OR " + NG + " = '' OR " + NG  + " = ' '"
        MakeFeatureLayer_management(fc, fl, wc)
    else:
        MakeFeatureLayer_management(fc, fl)

    #define the field list
    fields = (xField, yField, NG, "SHAPE@X", "SHAPE@Y") #modify this to access the shape field

    #get desired spatial reference
    sr = SpatialReference("WGS 1984")

    #get current spatial reference
    sr_org = Describe(fc).SpatialReference

    #calculate the NG coordinate for each row
    try:
        with UpdateCursor(fl, fields) as cursor:
            for row in cursor:
                #see if the x/y fields are blank or are populated
                if row[0] is None or row[0] == 0:
                    #create new point object
                    point = Point()
                    point.X = row[3]
                    point.Y = row[4]

                    #convert to a point geometry
                    pointGeom = PointGeometry(point, sr_org)

                    #reproject the point geometry into WGS 1984
                    point2 = pointGeom.projectAs(sr, "WGS_1984_(ITRF00)_To_NAD_1983")

                    #turn the point geometry back into a normal point with the "first point" functionality
                    firstPoint = point2.firstPoint

                    #get the x/y position
                    x = firstPoint.X
                    y = firstPoint.Y

                    #update the x & y fields along the way
                    row[0] = x
                    row[1] = y
                else:
                    x = row[0]
                    y = row[1]

                #some error trapping, just in case...
                if x is not None:
                    if y is not None:
                        #convert the x & y coordinates to USNG and update the field
                        row[2] = ct.AsMGRS([y,x], 5, False)
                cursor.updateRow(row)

        #release the locks on the data
        del row
        del cursor

        AddMessage("Lat/Long and USNG coordinates successfully updated.")
    except:
        AddMessage("Lat/Long and USNG coordinates could not be updated.")

    finally:
        # Stop the edit operation.
        edit.stopOperation()

        # Stop the edit session and save the changes
        edit.stopEditing(True)

    AddMessage("Processing complete.")