-
Notifications
You must be signed in to change notification settings - Fork 0
/
Temple_Locator.py
308 lines (266 loc) · 16.9 KB
/
Temple_Locator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# Project1.py
# Created on: 2016-01-19 11:53:32.00000
# (generated by ArcGIS/ModelBuilder)
# Description:
# ---------------------------------------------------------------------------
# Set the necessary product code
# import arcinfo
# Import arcpy module
import urllib2
import os
import arcpy
from bs4 import BeautifulSoup
import requests
# Check out any necessary licenses
arcpy.CheckOutExtension("spatial")
files_directory = arcpy.GetParameterAsText(0)
template_layer_boundary = arcpy.GetParameterAsText(1)
template_layer_raster = arcpy.GetParameterAsText(2)
output_directory = arcpy.GetParameterAsText(3)
geodatabase = arcpy.GetParameterAsText(4)
user_specified_paths = [files_directory, template_layer_boundary, template_layer_raster, output_directory, geodatabase]
try:
for path in user_specified_paths:
if not os.path.exists(path):
raise IOError(path)
arcpy.env.overwriteOutput = True
arcpy.env.workspace = geodatabase
arcpy.env.outputCoordinateSystem = arcpy.SpatialReference("WGS 1984 Web Mercator (Auxiliary Sphere)")
# Local initial data variables:
road_polylines = None
state_boundary = None
population_polygons = None
stake_center_locations = "stake_center_locations"
demfile = None
# Local map document variables
mxd = arcpy.mapping.MapDocument("current")
cdf = arcpy.mapping.ListDataFrames(mxd)[0]
legend = arcpy.mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT")[0]
# Local intermediate variables
Stake_Centers_Buffer = "Stake_Centers_Buffer"
DEM_State = "DEM_State"
Roads_Buffer = "Roads_Buffer"
Road_Stake_Intersect = "Road_Stake_Intersect"
Dense_Pop_Select = "Dense_Areas"
Road_Stake_Pop_Intersect = "Road_Stake_Pop_Intersect"
Slope_Raster = "Slope_Raster"
Dense_Pop_Polygons = "Dense_Pop_Polygons"
Pop_Buffer = "Pop_Buffer"
Pop_Agg_Table = "Pop_Agg_Table"
Polygon_To_Raster = "Polygon_To_Raster"
US_StateNames = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado',
'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho',
'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
'Maine' 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada',
'New Hampshire', 'New Jersey', 'New Mexico', 'New York',
'North Carolina', 'North Dakota', 'Ohio',
'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah',
'Vermont', 'Virginia', 'Washington', 'West Virginia',
'Wisconsin', 'Wyoming']
# Checks for existing pdf's. If prexisting, delete. Creates new pdf.
final_pdf_path = output_directory + "\\Temple_Site_Locations.pdf"
if os.path.exists(final_pdf_path):
os.remove(output_directory + "\\" + directory + ".pdf")
final_pdf = arcpy.mapping.PDFDocumentCreate(final_pdf_path)
# Searches for DEM folder containing DEM data.
dem_directory_path = os.path.join(files_directory, "DEM")
for filename in os.listdir(dem_directory_path):
if filename.endswith(".tif"):
# returns a complete file path as a string.
demfile = os.path.join(dem_directory_path, filename)
pagecounter = 0
for directory in os.listdir(files_directory):
if directory in US_StateNames:
if os.path.exists(output_directory + "\\" + directory + ".pdf"):
os.remove(output_directory + "\\" + directory + ".pdf")
# Formatting the state names to match the URL.
modified_state_name = directory.replace(' ', '-')
arcpy.AddMessage("Starting processing for " + directory + "...")
pagecounter += 1
arcpy.AddMessage("Scraping stake center data off the web...")
# Opens the webpage and scrapes.
webpage = urllib2.urlopen('http://www.ldschurchtemples.com/statistics/units/united-states/' + modified_state_name)
soup = BeautifulSoup(webpage.read(), 'html.parser')
stake_name_elements = []
# searches for specified tags. Finds stake names.
for link in soup.findAll("tr"):
if link.get("onclick") is not None:
if "stake" in link.get("onclick"):
stake_name_elements.append(link.get("onclick"))
# loops through the stake names and saves the URL appendage.
stake_name_links = []
for link in stake_name_elements:
i = link.find("/")
if i != -1:
stake_name_links.append(link[i:])
# Loops through HTML of different stakes to find tags containing addresses. Stores in a list.
stake_addresses = []
for link in stake_name_links:
newwebpage = urllib2.urlopen('http://www.ldschurchtemples.com' + link)
newsoup = BeautifulSoup(newwebpage.read(), 'html.parser')
for address in newsoup.findAll("td", class_="wrap"):
stake_addresses.append(address.getText())
# empty lists that store latitudes and longitudes.
stake_lats = []
stake_lons = []
# Loops through addresses, converts to lats and lons and stores in the above lists.
for stakeaddress in stake_addresses:
url = 'https://maps.googleapis.com/maps/api/geocode/json'
params = {'sensor': 'false', 'address': str(stakeaddress)}
r = requests.get(url, params=params)
results = r.json()['results']
stakelocation = results[0]['geometry']['location']
stake_lats.append(stakelocation['lat'])
stake_lons.append(stakelocation['lng'])
# converts lats and lons to arcmap points in a shapefile.
arcpy.AddMessage("Creating point shapefile of stake center locations...")
pointList = [list(a) for a in zip(stake_lats, stake_lons)]
point = arcpy.Point()
pointGeometryList = []
for pt in pointList: # creates the feature to store lat and lon from data
point.X = pt[1]
point.Y = pt[0]
pointGeometry = arcpy.PointGeometry(point).projectAs(arcpy.SpatialReference(4326))
pointGeometryList.append(pointGeometry)
arcpy.CopyFeatures_management(pointGeometryList, stake_center_locations)
state_directory_path = os.path.join(files_directory, directory)
# Stores data as variables to be used later in geoprocessing.
for data_directory in os.listdir(state_directory_path):
if data_directory == "Population":
arcpy.AddMessage("Extracting population data...")
state_data_directory = os.path.join(state_directory_path, data_directory)
for filename in os.listdir(state_data_directory):
if filename.endswith(".shp"):
population_polygons = str(os.path.join(state_data_directory, filename))
elif data_directory == "Roads":
arcpy.AddMessage("Extracting roads data...")
state_data_directory = os.path.join(state_directory_path, data_directory)
for filename in os.listdir(state_data_directory):
if filename.endswith(".shp"):
road_polylines = os.path.join(state_data_directory, filename)
elif data_directory == "Boundary":
arcpy.AddMessage("Extracting boundary data...")
state_data_directory = os.path.join(state_directory_path, data_directory)
for filename in os.listdir(state_data_directory):
if filename.endswith(".shp"):
state_boundary = os.path.join(state_data_directory, filename)
# Process: Add area field to population polygons
arcpy.AddMessage("Adding area field to population shapefile...")
arcpy.AddField_management(population_polygons, "AREA", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
# supplies the field with values for each polygon.
arcpy.AddMessage("Calculating area of population shapefile...")
arcpy.CalculateField_management(population_polygons, "AREA", "!shape.area@squaremiles!", "PYTHON_9.3", "")
# Process: Add an empty density field.
arcpy.AddMessage("Adding density field to population shapefile...")
arcpy.AddField_management(population_polygons, "DENSITY", "FLOAT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
# Process: Calculate the density field. Additional python code to catch division by zero for populations that were 0.
arcpy.AddMessage("Calculating density of population shapefile...")
expression = "ReClass(!AREA!, !POP10!)"
codeblock = """def ReClass(AREA, POP10):
x = -1.00
if (AREA == 0):
x = 0.00
else:
x = ( float(POP10) / float(AREA) )
return float(x)"""
# applies the previous code to the geoprocessing tool.
arcpy.CalculateField_management(population_polygons, "DENSITY", expression, "PYTHON_9.3", codeblock)
# Selects densely populated areas (greater than 1000 people per square mile).
arcpy.AddMessage("Selecting densely populated area polygons...")
arcpy.Select_analysis(population_polygons, Dense_Pop_Select, "\"DENSITY\" > 1000")
# Process: Combining closely distributed densely populated areas into multiple larger polygons.
arcpy.AddMessage("Aggregating densely populated area polygons...")
arcpy.AggregatePolygons_cartography(Dense_Pop_Select, Dense_Pop_Polygons, "2 Miles", "0 SquareMeters", "0 SquareMeters", "NON_ORTHOGONAL", "", Pop_Agg_Table)
# Process: Removes DEM data outside of the current state boundary.
arcpy.AddMessage("Extracting the current state portion of the US DEM...")
arcpy.gp.ExtractByMask_sa(demfile, state_boundary, DEM_State)
# Process: Calculates the slope of the state DEM.
arcpy.AddMessage("Calculating slope of DEM...")
Slope_Raster = arcpy.sa.Slope(DEM_State, "DEGREE", "1")
Slope_Raster.save("Slope_Raster")
# Process: Reclassifies the DEM so that anything less than 15 degrees is assigned the value of 1 and everything else is assigned the value of 0.
arcpy.AddMessage("Reclassifying slope of DEM...")
Slope_Reclass = arcpy.sa.LessThan(Slope_Raster, 15)
Slope_Reclass.save("Slope_Reclass")
# Process: Creates a 2 mile buffer around primary and secondary roads.
arcpy.AddMessage("Applying buffer to roads...")
arcpy.Buffer_analysis(road_polylines, Roads_Buffer, "2 Miles", "FULL", "ROUND", "NONE", "", "PLANAR")
# Process: 5 mile Stake Center Buffer
arcpy.AddMessage("Applying buffer to stake centers...")
arcpy.Buffer_analysis(stake_center_locations, Stake_Centers_Buffer, "5 Miles", "FULL", "ROUND", "NONE", "", "PLANAR")
# Process: Intersects the road buffers with the stake center buffers.
arcpy.AddMessage("Applying intersect to roads and stakes")
arcpy.Intersect_analysis([Roads_Buffer, Stake_Centers_Buffer], Road_Stake_Intersect, "ALL", "", "INPUT")
# Process: Buffering the population polygons.
arcpy.AddMessage("Applying buffer to population area")
arcpy.Buffer_analysis(Dense_Pop_Polygons, Pop_Buffer, "1 Miles", "FULL", "ROUND", "NONE", "", "PLANAR")
# Process: Intersecting all the buffers.
arcpy.AddMessage("Applying intersect to population and stakeroad buffer")
arcpy.Intersect_analysis([Road_Stake_Intersect, Pop_Buffer], Road_Stake_Pop_Intersect, "ALL", "", "INPUT")
# Process: Convert the polygon to raster.
arcpy.AddMessage("Converting Road_Stake_Pop_Intersect polygon to raster")
arcpy.PolygonToRaster_conversion(Road_Stake_Pop_Intersect, "Shape_Area", Polygon_To_Raster, "CELL_CENTER", "NONE", "10")
# Process: Everything in this raster is assigned the value of 1 because it's all acceptable.
arcpy.AddMessage("Reclassifying Road_Stake_Pop_Intersect raster")
Raster_Reclass = arcpy.sa.GreaterThan(Polygon_To_Raster, 0)
Raster_Reclass.save("Raster_Reclass")
# Process: Performs the raster calculator to remove unacceptable locations with slopes greater than 15 degrees.
arcpy.AddMessage("Running Raster calculator on Slope and Road_Stake_Pop_Intersect")
Possible_Locations = Raster_Reclass * Slope_Reclass
Possible_Locations.save("Possible_Locations")
# Process: Creates the possible locations layer and state boundary layers.
possible_locations_layer = arcpy.mapping.Layer("Possible_Locations")
possible_locations_layer.name = "Possible Locations"
state_boundary_layer = arcpy.mapping.Layer(state_boundary)
state_boundary_layer.name = "State Boundary"
# Process: Adding layers to map
legend.autoAdd = True # Add the possible locations legend item
arcpy.mapping.AddLayer(cdf, possible_locations_layer, "TOP")
legend.autoAdd = False # Don't add the boundary layer legend item
arcpy.mapping.AddLayer(cdf, state_boundary_layer, "TOP")
# zooms to the state boundary extents.
lyr = arcpy.mapping.ListLayers(mxd, "State Boundary", cdf)[0]
ext = lyr.getExtent()
cdf.extent = ext
lyrFile = arcpy.mapping.Layer(template_layer_boundary) # Gets the symbol layer for state boundary
arcpy.mapping.UpdateLayer(cdf, lyr, lyrFile, True) # Updates symbology
lyr = arcpy.mapping.ListLayers(mxd, "Possible Locations", cdf)[0]
lyrFile = arcpy.mapping.Layer(template_layer_raster) # Gets the symbol layer for the possible locations raster
arcpy.mapping.UpdateLayer(cdf, lyr, lyrFile, True) # updates the symbology
# changes text size for the title and page number before printing to pdf.
for elem in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
if elem.text == "Title:":
elem.text = "<FNT size=\'36\'>Temple Locations for " + directory.capitalize() + "</FNT>"
if elem.text == "Page:":
elem.text = "<FNT size=\'20\'>Page " + str(pagecounter) + "</FNT>"
arcpy.RefreshActiveView()
# performs an empty loop to stall the program and allow processing to catch up. Prevents program from freezing.
for j in range(500):
pass
# Printing the map to a pdf with the path chosen from the parameters above. Newly created pdf is added to the final combined pdf document.
page_pdf_path = output_directory + "\\" + directory + ".pdf"
arcpy.mapping.ExportToPDF(mxd, page_pdf_path)
final_pdf.appendPages(page_pdf_path)
# Restores the text to its default setting in the PDF template.
for elem in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"): # changes text elements back
if elem.text == "<FNT size=\'36\'>Temple Locations for " + directory.capitalize() + "</FNT>":
elem.text = "Title:"
if elem.text == "<FNT size=\'20\'>Page " + str(pagecounter) + "</FNT>":
elem.text = "Page:"
arcpy.RefreshActiveView()
# removes layers from the previous map.
for layer in arcpy.mapping.ListLayers(mxd):
if layer.name == "State Boundary" or layer.name == "Possible Locations":
arcpy.mapping.RemoveLayer(cdf, layer)
# saves and closes the pdf after program as looped through all the states.
final_pdf.saveAndClose()
final_pdf = arcpy.mapping.PDFDocumentOpen(final_pdf_path)
except IOError, ex:
arcpy.AddMessage("The path %s does not exist. Please check file path and retry." % ex.args[0])
except Exception, ex:
arcpy.AddMessage("Please check your internet connection or check if the website: http://www.ldschurchtemples.com is down.")
arcpy.AddMessage("Script finished.")