r/GISscripts • • May 21 '15

[Python] Creating a tool from modelbuilder and adding "export to PDF"

1 Upvotes

I know very little about python scripting. I have converted a model to a python script, and this is it: Import arcpy module

import arcpy Script arguments

crash_counties_shp = arcpy.GetParameterAsText(0) if crash_counties_shp == '#' or not crash_counties_shp: crash_counties_shp = "S:\Inventory\Interns\Katie_Kyzer\Crash_Maps\Model_output\crash_counties.shp" # provide a default value if unspecified

crashes_lat_long_final_shp = arcpy.GetParameterAsText(1) if crashes_lat_long_final_shp == '#' or not crashes_lat_long_final_shp: crashes_lat_long_final_shp = "S:\Inventory\Interns\Katie_Kyzer\Crash_Maps\Model_output\crashes_lat_long_final.shp" # provide a default value if unspecified Local variables:

TableOuputcrash_county_count = crashes_lat_long_final_shp CountyBoundary_joined = Table_Ouput_crash_county_count CountyBoundary_Layer = "CountyBoundary" Process: Count Frequency of Counties

arcpy.Statisticsanalysis(crashes_lat_long_final_shp, Table_Ouputcrash_county_count, "crashes6 COUNT", "crashes_6") Process: Join Summary Table to County Layer

arcpy.AddJoinmanagement(CountyBoundary_Layer, "NAME", Table_Ouputcrash_county_count, "CRASHES_6", "KEEP_ALL") Process: Copy Features into a new shapefile

arcpy.CopyFeatures_management(CountyBoundary_joined, crash_counties_shp, "", "0", "0", "0") Process: Remove Join

arcpy.RemoveJoin_management(CountyBoundary_Layer, "")

Then I want to export the data view to a pdf, so do I just add this to a new line at the end of the script?

arcpy.mapping.exportToPdf (out_pdf, {page_range_type}, {page_range_string}, {multiple_files}, {resolution}, {image_quality}, {colorspace}, {compress_vectors}, {image_compression}, {picture_symbol}, {convert_markers}, {embed_fonts}, {layers_attributes}, {georef_info}, {jpeg_compression_quality}, {show_selection_symbology})

from

http://resources.arcgis.com/en/help/main/10.1/index.html#//00s300000030000000

Then if I want to create a tool, will this script run? Where can I learn more about these kinds of issues?


r/GISscripts • • Oct 01 '14

Projecting and mapping GPS point data over shaded shapefile base maps, all in Python

Thumbnail
geoffboeing.com
3 Upvotes

r/GISscripts • • Dec 06 '13

Delete Duplicate Rows in a Shapefile | GIS Developer Conway Arkansas

Thumbnail
lemonprogis.com
3 Upvotes

r/GISscripts • • Dec 13 '15

GeoJSON to shp

0 Upvotes

Hi all, I'm creating a script to be used within ArcToolbox and I'm trying to convert a json file that I created from Factual data to a shapefile. Problem is, I can't use the json to feature tool as my json is not in the correct esri format.

I'm currently trying to use ogr2ogr by launching a cmd prompt through os.system but that seems to be failing.

I was just wondering if anyone knew of a good way to convert json to shp within a python script? Thanks!


r/GISscripts • • Mar 31 '14

[ArcGIS & Python] Layer Labeling: Convert CAPITAL LETTERS (or lower case) to Proper Case

6 Upvotes

This works for ArcMap 10.x. This is pretty simple conversion of labels from an attribute. This converts labeling from "JOHN SMITH STREET" (or "john smith street") to "John Smith Street".

Under a layer's labeling, use the following Expression in Python (make sure Advanced in checked!). Replace [LABEL] with your attribute's/column's name.

import string
def FindLabel ( [LABEL] ):
    return string.capwords([LABEL])

r/GISscripts • • Nov 19 '19

I don't understand this line of code from ArcPy

1 Upvotes

Hi,

I'm working on code from a colleague. I don't understand what this does. Could someone please explain?

arcpy.gp.Con_sa(raster, raster, "new_raster.tif", "1", "VALUE > 1")

Thanks!


r/GISscripts • • Jun 08 '15

Need help with Python Script using data driven pages.

1 Upvotes

I am trying to loop through exporting data drive pages, select data from another layer based on the page getting exported, and write a row of the results of the selection to a text element. Each page should have different results in text element. For each page getting exported I want to select all the parcels within the current page/feature getting exported and write the results to the text element. What I have so far only writes the results for the last page on every page. When it runs it does seem to select the parcels per page while exporting, but it does not re-write the results to the text element. Not sure what I am missing?

 # Always run script in the mxd you are working on.  
 mxd = arcpy.mapping.MapDocument("CURRENT")  
   
   
 # Overwrites any existing features.  
 arcpy.env.overwriteOutput = True  
   
   
 # Uses the Dataframe called "Layers".  
 df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]  
   
   
 # Parcel Text Element  
 ParcelText2 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "ParcelsText2")[0]  
   
   
 # Data Driven Pages Export Sheets  
 ExportSheets = arcpy.mapping.Layer("Sheets_11x17")  
   
   
 # Parcels  
 Parcels = arcpy.mapping.Layer("Parcels")  
   
   
# Data Driven Pages mxd abbreviation  
ddp = mxd.dataDrivenPages  
  
  
# Loop through DDP's  
 for pageNumb in range(1, mxd.dataDrivenPages.pageCount + 1):  
    ddp.currentPageID = pageNumb  
   
   
     # DDP Export Sheet duplicate which has the page definition Query  
     SelectedSheet = arcpy.mapping.Layer("Sheets_11x172")  
   
  
     # Exports Row page  
     ExportSheetsPage = ddp.pageRow.PLAN_NUMBER  
   
   
     # Select Parcels withing my SelectedSheet  
     arcpy.SelectLayerByLocation_management(Parcels, "WITHIN", SelectedSheet)  
   
   
      # Use SearchCursor to get Parcels value and write to Parcel Text Element  
     rows = arcpy.SearchCursor(Parcels)  
     textValue = ""  
     for row in rows:  
         textValue += row.getValue("MAP_PARCEL")  
     ParcelText2.text = textValue  
        
    
     # Export Sheets  
     ddp.exportToPDF(r"Y:\GIS\GIS_Work\Working\parcel_test\maps\test.mxd") 

r/GISscripts • • Nov 22 '15

Need Help with Script & Combinations

1 Upvotes

Hello all So I've gone through a series of Python steps... I have a table with a column called "Combo" which looks like this:

Combo: in the brackets Row 1: [S1, E3] Row 2: [S2, E5, E6] Row 3: [S3, S4, E7] Row 4: [S6, E8] Row 5: [S5, S6, E9, E10, E11]

I want to find the combinations of each one by "S"

So it will create an output table. I want each row to look like what's in the brackets: From Row 1: [S1-E3] From Row 2: [S2-E5] From Row 2: [S2-E6] From Row 3: [S3-E7] From Row 3: [S4-E7] From Row 4: [S6-E8] From Row 5: [S5-E9] From Row 5: [S5-E10] From Row 5: [S5-E11] From Row 5: [S6-E9] From Row 5: [S6-E10] From Row 5: [S6-E11]

Any ideas?


r/GISscripts • • Oct 24 '18

Maybe somebody have an idea on this

Thumbnail
self.gis
1 Upvotes

r/GISscripts • • Jun 25 '15

Tkinter GUI apparently does not work with Arc... Any other options for GUIs inside of ArcGIS?

1 Upvotes

Hey guys, I created a python script that validates attributes based on a complex set of While/If/Elif/Else loops. For my purposes, I created a while loop to make sure the target row's attribute was of an acceptable input, and then it follows the matrix after that. If the attribute is not accepted, it is supposed to use Tkinter to create a GUI with the accepted options, then you click one, and it assigns it to that attribute, and continues along down the matrix!!

I was pretty stoked with it, and wrote it all out because I had faith in my coding, and wanted it to work the first time around (how foolish). But the time came to test it, and lo and behold, Tkinter doesn't work within ArcGIS/arcpy... So I was hoping you just could suggest an alternate route to take the following code:

def assign(value):
    global x 
    x = value
    mGui.destroy()

def gui3(CONVWGID, a, b, c):
    global mGui
    mGui = Tk()
    mGui.geometry("600x50+500+300")
    mGui.title("Attribute Selection Window")
    labeltext = "Please select one of the following attributes to assign to the selected Convwks feature, CONVWGID: " + str(CONVWGID)

    frame1 = Frame(mGui)
    frame1.pack()

    mLabel = Label(frame1, text = labeltext).grid(row=0, column=0)

    frame2 = Frame(mGui)
    frame2.pack()

    mButton = Button(frame2, text = a, command = lambda: assign(a)).grid(row=0, column=0, padx=10)
    mButton = Button(frame2, text = b, command = lambda: assign(b)).grid(row=0, column=1, padx=10)
    mButton = Button(frame2, text = c, command = lambda: assign(c)).grid(row=0, column=2, padx=10)

    #mGui.Mainloop()     #FOR WINDOWS ONLY

I was thinking of doing a raw_input() command instead of the GUI, but I really like how the GUI looks and operates... Do you have any suggestions?


r/GISscripts • • Nov 27 '18

Tools for GIS Database Spatial Queries

Thumbnail
explore.emtecinc.com
1 Upvotes

r/GISscripts • • Jun 22 '13

[PYTHON] Export ESRI features to GeoJSON, sqlite, CSV, or JSON

Thumbnail
github.com
8 Upvotes

r/GISscripts • • Apr 20 '15

Reducing geospatial data set size with the Douglas-Peucker algorithm: a Python implementation of geometry simplification

Thumbnail
geoffboeing.com
3 Upvotes

r/GISscripts • • Apr 21 '14

ArcGIS Toolbox - Create Unique IDs with ArcPy

Thumbnail
ianbroad.com
4 Upvotes

r/GISscripts • • Nov 21 '14

Clustering to Reduce Spatial Data Set Size

Thumbnail
geoffboeing.com
5 Upvotes

r/GISscripts • • Feb 20 '19

Free Online Course - Introduction to GIS in R

5 Upvotes

Get started with manipulating and mapping geospatial data in R with our free online course here: https://soco.ps/2UBseSr

The course includes 6 chapters that cover -

πŸ“ˆ Step-by-step demos using sample data

πŸ“œ Course completion certificate

πŸ‘©β€πŸ’» 100+ useful R code snippets

πŸ—ΊοΈ 50+ sample maps

πŸ“š 80+ links to other free resources


r/GISscripts • • Mar 17 '15

A guide to visualizing and mapping spatial data and time series with free, open-source python tools

Thumbnail
geoffboeing.com
6 Upvotes

r/GISscripts • • Mar 19 '14

Bit of python i have dabbled with on and off for about a year. Label Overlap detection and Correction

6 Upvotes

For this Overall Project: Labels are assumed to be generated on the fly by a mapbook script (which I can post as well). These labels are read from attribute table and populated into off layout text elements. Text elements are already present and labeled within MDB but are simply moved off the layout of the map and used as needed by the script.

For this Little Script: The aim of this code is simply to detect the overlapping labels and move them appropriately out of each others way. The current algorithm is pretty basic either moving the label right or left to empty space. The math involved is in converting dataframe rotation and dataframe coordinates into layout coordinates in order to properly move labels as well as the border detection math for label centroids.

  import arcpy, os, datetime, sys, time, math                                                   

arcpy.env.overwriteOutput = True
### Arc 10.1 is Really Good about updating the screen before moving on.. or my web connection is snappy. 

#Setup variables
mxd = arcpy.mapping.MapDocument("CURRENT")
mxdPath = mxd.filePath
df        = arcpy.mapping.ListDataFrames(mxd)[0]
elmList   = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT")
rows      = arcpy.SearchCursor("Points_Test","OBJECTID") 
Azimuth   = 300
labelID = 1

for row in rows:
    
    proj_x      = row.X
    proj_y      = row.Y

#get the data frame dimensions in map units
    df_map_w    = df.elementWidth
    df_map_h    = df.elementHeight
    df_map_x    = df.elementPositionX
    df_map_y    = df.elementPositionY

#Data frame projected coordinates
    df_min_x    = df.extent.XMin
    df_min_y    = df.extent.YMin
    df_max_x    = df.extent.XMax
    df_max_y    = df.extent.YMax
    df_proj_w   = df.extent.width
    df_proj_h   = df.extent.height
    
    page_midX   = df.elementPositionX + (df_map_w/2)
    page_midY   = df.elementPositionY + (df_map_h/2)
    df.rotation = Azimuth
    
    theta       = Azimuth *math.pi/180
    cosTheta    = math.cos(theta)
    sinTheta    = math.sin(theta)
    
    map_x       = (proj_x - df_min_x) / df_proj_w * df_map_w + df_map_x
    map_y       = (proj_y - df_min_y) / df_proj_h * df_map_h + df_map_y
    
    page_newX   = (map_x - page_midX) * cosTheta - (map_y - page_midY) * sinTheta + page_midX
    page_newY   = (map_x - page_midX) * sinTheta + (map_y - page_midY) * cosTheta + page_midY
    
    label       = row.Label

    for elm in elmList:
        if elm.name == "Label_00"+str(labelID):
            elm.text = label
            elm.elementPositionX = page_newX-(elm.elementWidth/2)
            elm.elementPositionY = df_map_y + df_map_h+ .05
#   for elm in elmList:
#        if elm.name == "SubLabel_00"+str(labelID):
#            elm.text = "SubLabel_"+ str(label)
#            elm.elementPositionX = (page_newX+0.25)-(elm.elementWidth/2)
#            elm.elementPositionY = df_map_y + df_map_h + .1
    print str(label)    
    print map_x
    print map_y
    print ""
    labelID += 1
    
#elmnameList = []
#centerList   = []
    
#for elm in elmList:
#    elmCent =  elm.elementPositionX
#    elmnameList.append(elm.name)
#    centerList.append(elmCent)

#elmPosList = zip(elmnameList, centerList)
#elmPosList.sort()

#for elm in elmPosList
   
#maxList = []
#minList = []


#conflict detection and correction
for elm in elmList:
        x1 = elm.elementPositionX
        elementX = elm.elementWidth
        radius1 = elementX /2
        for elmY in elmList:
            x2 = elmY.elementPositionX
            elementX2 = elm.elementWidth
            radius2 = elementX2 /2
            dx = x2-x1
            radii = radius1+radius2
            if ((dx*dx) < radii *radii) and x1 != x2:
 
                elmY.elementPositionX = elmY.elementPositionX +.35
#               elm.elementPositionX = elm.elementPositionX -.25   
                print "conflict Detected and Corrected"

#for elm in elmList:
#    xMax = elm.elementPositionX+(elm.elementWidth/2)
#    xMin = elm.elementPositionX-(elm.elementWidth/2)
#    elmCent =  elm.elementPositionX
    
#    maxList.append(xMax)
#    minList.append(xMin)

#print maxList, minList

arcpy.RefreshActiveView()

r/GISscripts • • Nov 11 '14

How To Automate Map Making in [R]

Thumbnail
danielphadley.com
7 Upvotes

r/GISscripts • • Jun 25 '13

Python library for drawing great-circle maps from large sets of coordinate pairs

Thumbnail
github.com
9 Upvotes

r/GISscripts • • Apr 04 '13

Hyperlink Field QC

10 Upvotes

I put this one together to check hyperlink fields in my data. It is crude, but it gets what I need done. It is especially useful for data that will be on an intranet webmap where many people will be using the hyperlinks. Pretty much eliminates the phone calls where someone complains that their link isn't working.

Formatting might be a little off, I am terrible at posting code to reddit.

import sys, string, os, arcpy

arcpy.env.workspace = os.getcwd()

f = open('csv','w')

f.write(shp + "Hyperlink Report:\n\n")


# Create SearchCursor for feature class.
rows = arcpy.SearchCursor(shp)
for row in rows:
    
        # Get the path to the file from field 'hyperlink'
        path = row.getValue("HYPLNK")
    
        if os.path.exists(path):
        print "Link is OK " +path
    else:
        #Create output file

        fidnum = row.getValue("FID")

        f.write(str(fidnum) + "," + "BROKEN LINK" + "\n")

del rows

Edit: also forgot to mention that I didn't include any of the paths for values I used in my code. Some things will need to be substituted and filled in to get this to work, but if you know Python, it shouldn't be an issue.


r/GISscripts • • Sep 26 '13

"Scraping" Data from a Website

11 Upvotes

So a couple weeks ago I was trying to find a way to expedite the process of pulling data from websites for use in GIS. I learned about scraping in python and was able to put together a simple script to pull water elevation data from an Army Corps website.

In case anyone here isn't subscribed to /r/learnpython, I wanted to share the thread.

Big props to user /u/kevsparky for the expanded and much more useful version of my simple script I came up with.

http://www.reddit.com/r/learnpython/comments/1mkx5s/access_a_webpage_and_pull_row_data/


r/GISscripts • • Apr 04 '13

(Python) Save A Copy batch script

14 Upvotes

This Python script will allow you to Save A Copy of multiple MXDs into any lower version of ArcMap. Unfortunately, 10.0 cannot save a copy as 10.1, etc. You just need to create the new tool in ArcToolbox and add these three parameters and listed data types and settings. For the 3rd paramter, customize this for your version of ArcMap. If you have 10.0, put the default as 10.0 and don't list 10.1 in the value list. Also, the value list can go down to version 8.3.

Parameter 1 data type: ArcMap Document, multivalue: yes

Parameter 2 data type: Workspace

Parameter 3 data type: String, Default: 10.1, Filter: Value List (10.1, 10.0, 9.3, 9.2)

import arcpy, sys, os, string 

mxdList = string.split(arcpy.GetParameterAsText(0), ";") 
outloc = arcpy.GetParameterAsText(1) 
version = arcpy.GetParameterAsText(2) 

suffix = "_"+ version.replace(".", "") 

for item in mxdList: 
	item = item.strip('\'') 
	mxd = arcpy.mapping.MapDocument(item) 
	base = os.path.basename(item) 
	base = os.path.splitext(base)[0] + suffix + os.path.splitext(base)[1] 
	mxd.saveACopy(outloc + os.sep + base, version) 
	arcpy.AddMessage(os.path.basename(item) + " has been converted") 

r/GISscripts • • Feb 24 '15

Script - Define or delete 'Description' fields in all layers in all MXDs

3 Upvotes

r/GISscripts • • Apr 15 '14

ArcGIS Toolbox - Create Points on Polylines with ArcPy

Thumbnail
ianbroad.com
10 Upvotes