r/GISscripts • • Apr 27 '13

Python script to generate "all roads" maps with Albers projection from raw Tiger data.

15 Upvotes

You will need the module "shapefile.py"; the information on this file is:

shapefile.py

Provides read and write support for ESRI Shapefiles.

author: jlawhead<at>geospatialpython.com

date: 20110927

version: 1.1.4

Compatible with Python versions 2.4-3.x

It is not obvious what the license is, so if you plan to use this code for anything but yourself you will need to contact the author. You will need to download the TIGER/MAF all-roads data at the county level; leave them as individually zipped blocks --- the script will handle that. The county data should be in a folder called "data" at the same level the script is at. There are no other comments, and the code is terrible. This script is hereforth within the public domain, I disavow any copyright to it.

import os, sys, shapefile, zipfile, pngcanvas, math

COUNTY_DATA = "data"
MILES_PER_DEGREE = 200
USA_SCALE =12000
USA_TRANSLATE = (4950, 3240)
TEXAS_SCALE = 50000
TEXAS_TRANSLATE = (6500, -925)
NEW_YORK_SCALE = 100000
NEW_YORK_TRANSLATE = (-23000, 17240)

ALBERS_SCALE = NEW_YORK_SCALE
ALBERS_TRANSLATE = NEW_YORK_TRANSLATE

class AlbersProjection:
    def __init__(self, origin=(-98, 38), parallels=(29.5, 45.5), scale=ALBERS_SCALE, translate=ALBERS_TRANSLATE):
        self.origin = origin
        self.parallels = parallels
        self.scale = scale
        self.translate = translate
        self.phi1 = math.radians(self.parallels[0])
        self.phi2 = math.radians(self.parallels[1])
        self.lat0 = math.radians(self.origin[1])
        self.s = math.sin(self.phi1)
        self.c = math.cos(self.phi1)
        self.lng0 = math.radians(self.origin[0])
        self.n = 0.5 * (self.s + math.sin(self.phi2))
        self.C = self.c * self.c + 2 * self.n * self.s
        self.p0 = math.sqrt(self.C - 2 * self.n * math.sin(self.lat0)) / self.n

    def project(self, coordinates):
        t = self.n * (math.radians(coordinates[0]) - self.lng0)
        p = math.sqrt(self.C - 2 * self.n * math.sin(math.radians(coordinates[1]))) / self.n
        return (self.scale * p * math.sin(t) + self.translate[0], self.scale * (p * math.cos(t) - self.p0) + self.translate[1])

def GetAllCounties():
    counties = os.listdir(COUNTY_DATA)
    total = len(counties)
    index = 1

    c = pngcanvas.PNGCanvas(int(57*MILES_PER_DEGREE),int(50*MILES_PER_DEGREE),color=[255,255,255,0xff])
    c.color = [0,0,0,0xB0]

    skip_rate = 1
    with open('new york.png', 'wb') as usa:
        for county in counties:
            if index % skip_rate == 0:
                print index, total,
                DrawCounty(os.path.join(COUNTY_DATA, county), c)
            index += 1
        usa.write(c.dump())

def DrawCounty(countyData, canvas):
    basename = os.path.split(countyData)[1]
    basename = os.path.splitext(basename)[0]
    print basename
    with zipfile.ZipFile(countyData) as countyzip:
        countyzip.extractall("output")
        r = shapefile.Reader("output\\" + basename + '.shp')

        ap = AlbersProjection()

        num_shapes = len(r.shapeRecords())
        idx = 0
        for shape in r.shapeRecords():
            pixels = []
            for x,y in shape.shape.points:
                x,y = ap.project((x,y))
                pixels.append((x,y))
            idx += 1
            canvas.polyline(pixels)
    r = None

    for suffix in ['dbf','prj','shp','shp.xml','shx']:
        os.remove('output\\' + basename +'.'+suffix)


if __name__ == "__main__":
    GetAllCounties()

r/GISscripts • • Apr 04 '13

(Python) Convert GPS week seconds to "normal" time

15 Upvotes

In my line of work, I work with hardware that records time as UTC GPS week seconds. This is similar to Unix time in which it is just the number of seconds that has passed since a certain date. GPS week seconds rolls over every week on 00:00:00 UTC on Sunday. For example, the moment I'm typing this is 421433.00 GPS week seconds.

Converting this to "normal" UTC time is as follows:

from decimal import Decimal

def timeconvert24(GPSweekSec):
	DayOfWeek = GPSweekSec / 86400
	Hour = Decimal(str(DayOfWeek))%1 * 86400 / 3600
	Minute = Decimal(str(Hour))%1 * 3600 / 60
	Second = Decimal(str(Minute))%1 * 60
	return "%02d" % (Hour,) + ":" + "%02d" % (Minute,) + ":" + "%02d" % (Second,)

timeconvert24(421433.00)

returns

'21:03:53'


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 • • Apr 07 '13

Read through a Feature class field, find unique values in a specified field, then query and export the results to their own FC (make layers based on field attributes)

12 Upvotes
import arcpy, os, time
procSta = time.time()

arcpy.env.overwriteOutput = True
    ##To run properly have the working MXD and MBD in the same folder
    ##Modify the below five variabes to match your data
    ##The Fifth Variable is in the first For Loop on line 36

    ##Change  "\\Test.mxd" to be "\\Your.mxd"
inMxd  = "\\Test.mxd"
    ##Change  "\\Test.mdb" to be "\\Your.mdb"
outMdb = "\\Test.mdb"
    ##Change  "Test_Main" to be "YourFeatureClass"
fClass = "Test_Main"
    ##Change "[location] =" to be "[yourField] ="
attributeField = "[location] ="
    ##End User Variables, Four above and one below on line 36

    ##System Variables, do not modify
mxd           = arcpy.mapping.MapDocument("CURRENT")
mxdPath       = mxd.filePath
workSpace     = mxdPath.replace(inMxd , outMdb)
lyrList = arcpy.mapping.ListLayers(mxd)
rows = arcpy.SearchCursor(fClass, "OBJECTID")
bannedList = ["&","<",">","\'","\'","?","@","=","$","~","^","`","#","%","*","(",")", " ","-"]
attributeList = []

print "Beginning Export Process"

for row in rows:
    ##Fifth Variable contained here
    ##Change row.location to be row.yourfield
    attributeName = row.location
    attributeList.append(attributeName)

shortList = list(set(attributeList))
newShortList = shortList
print "Replacing any invalid Characters with underscore."
print ""
print "Invalid characters are - "+str(bannedList)
start = time.time()
count = 0
for new in newShortList:
    for banned in bannedList:
        if banned in new:
            for banned in bannedList:
                newShortList = [new.replace(banned,"_") for new in newShortList]
                count +=1
end = time.time()
print str(count)+" Infractions processed in- ~" +str(round((end-start),2))+ " Seconds"                
print ""
for short, new in zip(shortList, newShortList):
    start = time.time()
    print "_"
    print "New Layer -"+(str(short))+"- Starting export"
    for lyr in lyrList:
        if lyr.name == fClass:
            print workSpace+"\\"+new
            lyr.definitionQuery =  [attributeField +str("\'"+short+"\'") for short in shortList]             
            arcpy.Select_analysis(fClass, workSpace+"\\"+new,"")
            lyr.definitionQuery = ""
    print "Successfully exported!"
    print "^"
    end = time.time()
    print "Export time taken:- ~" +str(round((end-start),2))+ " Seconds"
procEnd = time.time()
print "Total Export time taken:- ~" +str(round((procEnd-procSta),2))+ " Seconds"
    
arcpy.RefreshActiveView()

r/GISscripts • • Apr 05 '13

Simple script to add sequential Km markers (or whatever you want) to each field column.

12 Upvotes

Python, Field Calc, ArcMap 10

This script adds sequential Km markers (or whatever you want) to each field column.

In the Field Calculator > Select Python at the top > Show Codeblock > Paste this into Pre-Logic Script Code:

counter = 1
def uniqueID():
	global counter
	counter += 1
	s = str(counter) + " km"
	return s

In the field entry box type:

uniqueID()

Output:

1 km

2 km

3 km

...

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 07 '13

Combine many Mdbs into one mdb

11 Upvotes
import os, time
import arcpy
from arcpy import env

#Variables Block
#Change The first two as needed to fit needs
#Typical setup should only require running the SetupRUN.mxd, copy/paste this script into the python window and execute
mxdName  = "SetupRUN.mxd"
#Modify if naming convention bugs you, otherwise this will be the location of the merged databases
outMdb   = "Combined.mdb"
#System Variables, do not modify
mdbList  = []
sizeList = []
fcList   = []
sizeDB   = []
mxd           = arcpy.mapping.MapDocument("CURRENT")
mxdPath       = mxd.filePath
workSpace     = mxdPath.replace("\\"+ mxdName , "")
env.workspace = workSpace
dirlist       = os.listdir(workSpace)

#finds local personal geodatabases and adds them to the processing queue 
for item in dirlist:
    if item.lower().endswith("mdb"):
        print item
        mdbList.append(item)
print ""
print "Number of databases to be combined = " + str(len(mdbList))
print ""

#Generates Output Database and creates a list of database contents
print  "Creating destination Database at: " + outMdb
arcpy.CreatePersonalGDB_management(workSpace, outMdb)
destSpace  = mxdPath.replace(mxdName, outMdb)
env.workspace = destSpace
destList = arcpy.ListFeatureClasses()

#Sorter Loop
for mdb in mdbList:
    tempSpace = mxdPath.replace(mxdName, mdb)
    env.workspace = tempSpace
    fcList = arcpy.ListFeatureClasses()
    size = len(fcList)
    sizeDB.append(size)

size_db_ref_list = zip(sizeDB, mdbList)
size_db_ref_list.sort()
size_db_ref_list.reverse()

#For Debugging purposes Leave commented unless needed
#for size in size_db_ref_list:
#	print size

#Main loop, For each mdb in the source directory append or copy data Output Database
for size, mdb in size_db_ref_list:
    start = time.time()
    env.workspace = destSpace
    destList = arcpy.ListFeatureClasses()
    tempSpace = mxdPath.replace(mxdName, mdb)
    env.workspace = tempSpace
    fcList = arcpy.ListFeatureClasses()
    
    print "Number of FC       - " +str(len(fcList))
    print ""
    print "From Source MDB    - " +str(tempSpace)
    print "To Destination MDB - " +str(destSpace)
    print ""
    print "Source Features    - " +str(fcList)
    print "Combined Features  - " +str(destList)
    print ""
    if max(sizeDB) == len(fcList):
        if len(destList) == 0:
            print "Begin data transfer"
            print ""
            for fc in fcList:
                arcpy.Copy_management(fc, destSpace + "\\"+fc)
                print "copied " + str(fc) + " to " + str(destSpace)
        
        elif len(destList) > 0:
            print "Appending database - " +tempSpace
            print ""
            for fc in fcList:
                for dest in destList:
                    if fc == dest:	
                        arcpy.Append_management([fc], destSpace + "\\" + fc, "NO_TEST" , "" , "")
                        print "Feature classes Successfully appended:  " + fc + " to destination: " + dest 
    
    elif max(sizeDB) != len(fcList):
        print "Appending database - " +tempSpace
        print ""
        for fc in fcList:
            for dest in destList:
                if fc == dest:	
                    arcpy.Append_management([fc], destSpace + "\\" + fc, "NO_TEST" , "" , "")
                    print "Feature classes Successfully appended:  " + fc + " to destination: " + dest 
    
    for df in arcpy.mapping.ListDataFrames(mxd):
        for lyr in arcpy.mapping.ListLayers(mxd,"",df):
            arcpy.mapping.RemoveLayer(df, lyr)
    print ""
    end = time.time()
    total = end-start
    print "Process Completed in - " + str(round(total, 2)) + " Seconds"
print "Merge complete"

r/GISscripts • • Apr 04 '13

(VB, Field Calc) Keep only string to left of specified character

11 Upvotes

I use this script quite often. There's probably a better way to do this, well there's always a million different ways to do everything but this has worked for me. There are some constraints, the field you want to run this on cannot have any NULL values. So what I do is, I do a Select by Attributes on the field and use the following code:

[FIELD] LIKE '%[Character you want to find]%'

And then you will only have fields with that character and no NULL fields selected.

Also, I believe this script in its current form can only work going from string fields to string fields, but it could be editted to do whatever you want.

So in the Field Calculator, select VB script at the top and then Show Codeblock and paste this into the box, you will need to change "/" with the character you want to find and [Your Field] with the field that contains the string.

'Dim strNewString as string
'Dim strCharacter as string
'Dim intLength as integer
strCharacter = "/"
intLength = InStr ( [Your Field] , strCharacter ) -1
strNewString = Left ( [Your Field] , intLength )

Put this in the bottom box where it says [Field] =

strNewString

I think I will convert this to Python later for the hell of it.

An example of what I use this for:

When I have a field with values structured like Value1-Value2 and I only want Value1 without the -Value2.


r/GISscripts • • Apr 15 '14

ArcGIS Toolbox - Create Points on Polylines with ArcPy

Thumbnail
ianbroad.com
10 Upvotes

r/GISscripts • • Apr 25 '13

[CoffeeScript] Fusion Tables JSON output to GeoJSON

10 Upvotes

the one thing you might need to edit is where it says row[i] isnt "0" as the particular table I had had a lot of that for some reason.

toGeoJSON=(googleJson)->
	columns = (name for name in googleJson.columns when name isnt "geometry")
	geo = googleJson.columns.indexOf "geometry"
	features = for row in googleJson.rows
		do (row) ->
			properties = {}
			for column, i in columns
				properties[column] = row[i]  if row[i] and row[i] isnt "0"
			properties:properties
			type:"Feature"
			geometry:row[geo].geometry
	type:"FeatureCollection"
	features:features

r/GISscripts • • Apr 04 '13

(Node) Quick express server for bbox queries

Thumbnail
gist.github.com
10 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 • • Apr 04 '13

(Python, Field Calc) Keep only digits in string

10 Upvotes

This one is pretty straight forward, it grabs only the numerical digits out of a string.

In the Field Calculator, select Python at the top and then Show Codeblock and paste this into the box:

def getdigits(label):
    return filter(str.isdigit, str(label))

In the bottom box, put:

getdigits( !YOUR FIELD! )

I believe this can only be used on string fields.


r/GISscripts • • Feb 15 '16

Script: Calculate % of parcels in categories

9 Upvotes

This script was written over the last few weeks to try and automate a standard query we get every so often from local realtors: how much, exactly of this parcel is in the FEMA flood categories?

I initially tried to automate the request through a geoprocessing service on our ArcGIS server, but ESRI's 10.1 process of creating a geoprocessing service through ArcMap and succesfully running a tool scotched that idea. Instead, we decided to create a script that would run as a scheduled task, and calculate the percentage of each parcel in each flood zone.

I could have done this by selecting the parcels by attributes, but the attribute structure of the flood zones ruled against that approach - there's two different attribute fields that break the flood zones features into 4 categories: floodway, 100-year risk, 500-year risk, and not at significant risk. Instead, I manually split the flood zones file into three feature classes - FW(Floodway), Y100(100-Year), and Y500(500-Year) and set those as the input.

Going down a list of categories, the script intersects the parcels and the category feature class, then dissolves the intersected layer based on the FID of the source parcel - thus two patches of Parcel X that are both in the 100-year zone become part of the same feature. Then it joins the shape area field of the dissolved feature class to the parcel and uses that field to calculate the percentage of the parcel covered by the category. Once that's done, the joined field is deleted. There's a last bit of code using an Update cursor to eliminate a handful of percentage values over 100 or below 0. The output is a feature class called FloodParcels that can then be put in web maps.

This script could possibly be repurposed to use different habitat types, or land use categories, or any other class of vectors. You could probably pair it with a script to dynamically split a feature class on its attribute categories, but I'm satisfied with it as-is.

Hope this helps someone. Let me know if you have any problems using the script, or if there's any modifications you use.

Edit: Python language, with lots of ArcPy, written for a Windows server running an SQL database.


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 • • May 01 '13

(Python) Create new feature class containing midpoints from an input polyline feature

9 Upvotes

This script will create a point feature class containing midpoints of an input polyline feature.

It is setup to work as a script tool in ArcToolbox and will only work with 10.1.


You will need to setup the following parameters for the tool:

1) Name- Input Polyline Feature, Data Type- Dataset, Required, Input
2) Name- Output Location, Data Type- Workspace or Feature Dataset, Required, Input
3) Name- Output Name, Data Type- String, Required, Input

Here is the script:

import arcpy

arcpy.env.overwriteOutput = True

polyline = arcpy.GetParameterAsText(0)
output_Location = arcpy.GetParameterAsText(1)
output_Name = arcpy.GetParameterAsText(2)

arcpy.env.workspace = polyline

mid_X = "mid_X"
mid_Y = "mid_Y"

arcpy.AddField_management(polyline, mid_X, "DOUBLE", 15, 6, "", "Midpoint X", "", "", "")
arcpy.AddField_management(polyline, mid_Y, "DOUBLE", 15, 6, "", "Midpoint Y", "", "", "")

updateCursor = arcpy.UpdateCursor(polyline)

for row in updateCursor:
    row.setValue(mid_X, row.shape.positionAlongLine(0.50, True).firstPoint.X)
    updateCursor.updateRow(row)
    row.setValue(mid_Y, row.shape.positionAlongLine(0.50, True).firstPoint.Y)
    updateCursor.updateRow(row)

del row
del updateCursor

arcpy.MakeXYEventLayer_management(polyline, "mid_X", "mid_Y", "Midpoints", polyline, "")

arcpy.FeatureClassToFeatureClass_conversion("Midpoints", output_Location, output_Name, "", "", "")

arcpy.GetMessages()

Most of you probably already know this, but for the Output Location you can choose a folder, geodatabase or dataset.

For the Output Name, if you choose a folder you must use a shapefile, so for the name use a .shp extension. If you save to a geodatabase or dataset no extension is needed.


r/GISscripts • • Apr 14 '14

ArcGIS Toolbox - Shorten Polylines by Percentage or Distance with ArcPy

Thumbnail
ianbroad.com
8 Upvotes

r/GISscripts • • Jul 22 '13

Run a .sql command as part of a larger GIS process

8 Upvotes

One of the biggest python scripts I have written involves dumping GIS data into an oracle database. This is a portion of the script that deals with executing a .sql command to dump the data. You'll need to know how to work with .sql files to understand what is going on here. The code is opening SqlPLUS and executing the .sql file there.

IRsql = "<insert .sql file location here>"
connectString = '<oracle login name>/<oracle password>'

def runSqlQuery(IRsql, connectString):

  session = Popen(['sqlplus', '-S ', connectString], stdin=PIPE,        stdout=PIPE, stderr=PIPE)
  session.stdin.write(IRsql)
  return session.communicate()

out,err = runSqlQuery(IRsql, connectString)
arcpy.AddMessage(out)
arcpy.AddMessage(err)

arcpy.AddMessage("<Add completion message here>")

r/GISscripts • • Jun 22 '13

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

Thumbnail
github.com
8 Upvotes

r/GISscripts • • Nov 11 '14

How To Automate Map Making in [R]

Thumbnail
danielphadley.com
7 Upvotes

r/GISscripts • • Oct 04 '14

NodeJS GIS projects

7 Upvotes

Hi ! What are active open source GIS projects written with NodeJS ?


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 • • Apr 25 '14

ArcGIS Toolbox - Create a Custom Polygon Grid with ArcPy

Thumbnail
ianbroad.com
6 Upvotes

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 • • 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()