Select to view content in your preferred language

Convert x,y to lat, long

7280
14
Jump to solution
07-22-2015 10:09 AM
CCWeedcontrol
Frequent Contributor

I currently have a code that creates a point with a mouse click and works great, but i need the x,y to be calculated to lat and long. The current codes does that but it is slow and i use updatecursor. I would like to like to do the conversion when the ptGeometry, basically store it in the point when it gets created because with the current code it takes about 30 secs. I have tried to makefeaturelayer with the ptGeometry but and insert the lat long fields and then use the to update the point but i get nothing. so i need some help on how i can do this with the current code.

#import modules      
import arcpy      
"""   
tool box parameters   
point param = feature set   
targetpoint = featurelayer   
parcel = featurelayer   
"""    
arcpy.env.qualifiedFieldNames = False    
    
point = arcpy.GetParameterAsText(0)  #point boolen    
targetpoint = "CCAP" #target point feature class     
parcel = "parcels"  #target feature class    
parcel_lyr = 'parcel_lyr'      
      
      
for prow in arcpy.da.SearchCursor(point,'SHAPE@XY'):      
    x,y = prow[0]    
del prow      
       
point1 = arcpy.Point(x, y)      
ptGeometry = arcpy.PointGeometry(point1)    
    
CC_list = []    
with arcpy.da.SearchCursor(targetpoint, ["AddressID"]) as cursor:    
    for row in cursor:    
        try:    
            if "CC" in row[0]:    
                CC_list.append(int(row[0].strip("CC")))       
        except TypeError:    
            pass            
del cursor    
    
CC_list.sort()    
AddressID = CC_list[-1] + 1    
AddressID = 'CC' + str(AddressID)    
       
arcpy.MakeFeatureLayer_management(parcel,parcel_lyr)      
arcpy.SelectLayerByLocation_management(parcel_lyr,"INTERSECT",ptGeometry)      
      
fldList = ['ACCOUNT','OwnerName','SiteAddres','SiteNum','siteNumSfx','Predir','SiteStreet', 'StreetType', 'Postdir', 'SiteCity', 'SiteZip']      
fldDict ={}      
    
#Check that we only have one parcel and get the attributes from it    
if int(arcpy.GetCount_management(parcel_lyr).getOutput(0))==1:      
    for parrow in arcpy.da.SearchCursor(parcel_lyr,fldList):      
        for w in range(len(fldList)):      
            fldDict[fldList]=parrow      
    del parrow      
         
    targetFields = ['ACCOUNT', 'OwnerName', 'SiteAddres', 'SiteNum', 'siteNumSfx', 'Predir', 'Postdir', 'SiteCity', 'SiteZip',  
                    'SiteState', 'FacltyType', 'StructType', 'GIS_STEW', 'UpdateBy', 'Verified', 'Status', 'StructCat', 'APA_CODE',  
                    'AddressID', 'POINT_X', 'POINT_Y', 'StreetName','SHAPE@XY']     
          
    tprows = arcpy.da.InsertCursor(targetpoint, targetFields)  
    row = []  
    #Attributes from parcels  
    row.append(fldDict['ACCOUNT'])  
    row.append(fldDict['OwnerName'])  
    row.append(fldDict['SiteAddres'])  
    row.append(fldDict['SiteNum'])  
    row.append(fldDict['siteNumSfx'])  
    row.append(fldDict['Predir'])  
    row.append(fldDict['Postdir'])  
    row.append(fldDict['SiteCity'])  
    row.append(fldDict['SiteZip'])  
    #Preset attributes  
    row.append('ID')  
    row.append('Single Family Home')  
    row.append('Primary, Private')  
    row.append('CanyonCo')  
    row.append('TA')  
    row.append("Yes, GRM, TA")  
    row.append('Active')  
    row.append('Residential')  
    row.append('1110')  
    row.append(AddressID)  
    row.append(x)  
    row.append(y)  
    row.append(fldDict['SiteStreet'] + " " + fldDict['StreetType'])  
    row.append(point1)  
    tprows.insertRow(row)    
arcpy.RefreshActiveView()     
         
del tprows


#convert x,y to lat & long


latLonRef = "Coordinate Systems\Geographic Coordinate Systems\North America\NAD 1983.prj"   
featureClasses = arcpy.GetParameterAsText(0)   
featureClassesList = featureClasses.split(";")


for featureClass in featureClassesList: 
    rows = arcpy.UpdateCursor(targetpoint, "", latLonRef)
    for row in rows:
      feat = row.getValue("shape")
      cent = feat.centroid
    # To get the polygon area: cent = feat.area
      row.POINT_X = cent.Y
      row.POINT_Y = cent.X
      rows.updateRow(row)
      #arcpy.AddMessage(str(lat) + ", " + str(lon))

else:  
    arcpy.AddMessage("Number of parcels selected incorrect for this process")  

Message was edited by: 2CDSD 2C

0 Kudos
1 Solution

Accepted Solutions
DarrenWiens2
MVP Alum

That's because you're appending the variables 'x' and 'y' that you calculated at the beginning. If you want 'x' and 'y' to hold the lat/long values, you need to assign them as such.

x = pointA.centroid.X
y = pointA.centroid.Y 

...but now I'm not even sure what the 'point' feature set is supposed to be doing. Anyhow, I think your code has undergone so many revisions that you should really sit down and figure out what all your variables are doing.

View solution in original post

14 Replies
DarrenWiens2
MVP Alum

See this thread for how you can use arcpy.PointGeometry.projectAs() to change coordinate systems at the individual point level.

CCWeedcontrol
Frequent Contributor

i have tried the follwoing but getting an error.

Traceback (most recent call last):

  File "C:\GIS\Python\UpdateAddressPoints\CreatePointUdateAttributesTest6.py", line 29, in <module>

    pointA = point_utm.projectAs(arcpy.SpatialReference(115702))

  File "c:\program files (x86)\arcgis\desktop10.2\arcpy\arcpy\arcobjects\mixins.py", line 927, in __init__

    self._arc_object.createFromFile(item)

RuntimeError: ERROR 999999: Error executing function.

the input is not a geographic or projected coordinate system

#import modules        
import arcpy        
"""    
tool box parameters    
point param = feature set    
targetpoint = featurelayer    
parcel = featurelayer    
"""      
arcpy.env.qualifiedFieldNames = False      
      
point = arcpy.GetParameterAsText(0)  #point boolen      
targetpoint = "CCAP2" #target point feature class       
parcel = "parcels"  #target feature class      
parcel_lyr = 'parcel_lyr'        
        
        
for prow in arcpy.da.SearchCursor(point,'SHAPE@XY'):        
    x,y = prow[0]      
del prow        
         
point1 = arcpy.Point(x, y)        
ptGeometry = arcpy.PointGeometry(point1)      


#convert x,y to lat & long  


with arcpy.da.UpdateCursor(point,["POINT_X","POINT_Y"]) as cursor:  
    for row in cursor:
        point_utm = arcpy.PointGeometry(arcpy.Point(row[0],row[1]),arcpy.SpatialReference(103269))  
        pointA = point_utm.projectAs(arcpy.SpatialReference(115702)) 
        row[0]= pointA.centroid.X
        row[1]= pointA.centroid.Y
        cursor.updateRow(row) 
      
CC_list = []      
with arcpy.da.SearchCursor(targetpoint, ["AddressID"]) as cursor:      
    for row in cursor:      
        try:      
            if "CC" in row[0]:      
                CC_list.append(int(row[0].strip("CC")))         
        except TypeError:      
            pass              
del cursor      
      
CC_list.sort()      
AddressID = CC_list[-1] + 1      
AddressID = 'CC' + str(AddressID)      
         
arcpy.MakeFeatureLayer_management(parcel,parcel_lyr)        
arcpy.SelectLayerByLocation_management(parcel_lyr,"INTERSECT",ptGeometry)        
        
fldList = ['ACCOUNT','OwnerName','SiteAddres','SiteNum','siteNumSfx','Predir','SiteStreet', 'StreetType', 'Postdir', 'SiteCity', 'SiteZip']        
fldDict ={}        
      
#Check that we only have one parcel and get the attributes from it      
if int(arcpy.GetCount_management(parcel_lyr).getOutput(0))==1:        
    for parrow in arcpy.da.SearchCursor(parcel_lyr,fldList):        
        for w in range(len(fldList)):        
            fldDict[fldList]=parrow        
    del parrow        
           
    targetFields = ['ACCOUNT', 'OwnerName', 'SiteAddres', 'SiteNum', 'siteNumSfx', 'Predir', 'Postdir', 'SiteCity', 'SiteZip',    
                    'SiteState', 'FacltyType', 'StructType', 'GIS_STEW', 'UpdateBy', 'Verified', 'Status', 'StructCat', 'APA_CODE',    
                    'AddressID', 'POINT_X', 'POINT_Y', 'StreetName','SHAPE@XY']       
            
    tprows = arcpy.da.InsertCursor(targetpoint, targetFields)    
    row = []    
    #Attributes from parcels    
    row.append(fldDict['ACCOUNT'])    
    row.append(fldDict['OwnerName'])    
    row.append(fldDict['SiteAddres'])    
    row.append(fldDict['SiteNum'])    
    row.append(fldDict['siteNumSfx'])    
    row.append(fldDict['Predir'])    
    row.append(fldDict['Postdir'])    
    row.append(fldDict['SiteCity'])    
    row.append(fldDict['SiteZip'])    
    #Preset attributes    
    row.append('ID')    
    row.append('Single Family Home')    
    row.append('Primary, Private')    
    row.append('CanyonCo')    
    row.append('TA')    
    row.append("Yes, GRM, TA")    
    row.append('Active')    
    row.append('Residential')    
    row.append('1110')    
    row.append(AddressID)    
    row.append(x)    
    row.append(y)    
    row.append(fldDict['SiteStreet'] + " " + fldDict['StreetType'])    
    row.append(point1)    
    tprows.insertRow(row)      
arcpy.RefreshActiveView()       
           
del tprows  
  
  
#convert x,y to lat & long  
0 Kudos
DanPatterson_Retired
MVP Emeritus

115702   the input is not a geographic or projected coordinate system

Given the number and the error, is it correct or what is it supposed to be

0 Kudos
CCWeedcontrol
Frequent Contributor

it's going from projected coordinates to geographic coordinates.

0 Kudos
DarrenWiens2
MVP Alum

Try 4269 (the NAD83 geographic coordinate system) rather than 115702 (the NAD83 spheroid).

For reference:

Projected Coordinate Systems

Geographic Coordinate Systems

0 Kudos
CCWeedcontrol
Frequent Contributor

I made the change from 115702 to 4269 the code ran but the POINT_X and POINT_Y did not get converted, no error.

with arcpy.da.UpdateCursor(point,["POINT_X","POINT_Y"]) as cursor: 
    for row in cursor:
        point_utm = arcpy.PointGeometry(arcpy.Point(row[0],row[1]),arcpy.SpatialReference(103269)) 
        pointA = point_utm.projectAs(arcpy.SpatialReference(4269))
        row[0]= pointA.centroid.X
        row[1]= pointA.centroid.Y
        cursor.updateRow(row)
0 Kudos
DarrenWiens2
MVP Alum

Did you reload the table cache? If you have the table open, it won't automatically update until you reload it.

Anyhow, this code updates my table with lat/long, from UTM.

>>> with arcpy.da.UpdateCursor("coord_test",["ET_X","ET_Y"]) as cursor: 
        for row in cursor:
            point_utm = arcpy.PointGeometry(arcpy.Point(row[0],row[1]),arcpy.SpatialReference(26910)) 
            pointA = point_utm.projectAs(arcpy.SpatialReference(4269))
            row[0]= pointA.centroid.X
            row[1]= pointA.centroid.Y
            cursor.updateRow(row)
WesMiller
Deactivated User

point is a feature set and does not have fields "Point_X" or "Point_Y" try running Darren Wiens​ code on the targetpoint

0 Kudos
CCWeedcontrol
Frequent Contributor

if i run it against the target point it take 1 min. 7 secs, with no error. The point is created but the x,y are not lat long.

0 Kudos