Sunday, June 20, 2010

Saving Weather Stations to a Shapefile with Python

The National Weather Service offers several XML data feeds related to weather conditions. In this tutorial we will use the list of all national observation stations to create a shapefile of Washington stations with Python.

def createXMLfileFromURL(strURL,strOutFilePath):

#Open url and read
res = urllib2.urlopen(strURL)
data = res.read()

#Write data to file
writer = open(strOutFilePath,'w')
writer.write(data)
writer.close()

if __name__=='__main__':

#Grab the XML feed and write it to a file
noaaIndexXML = '/home/gregcorradini/XMLfeeds/indexNOAAII.xml'
createXMLfileFromURL('http://www.weather.gov/xml/current_obs/index.XML',noaaIndexXML)

#Use ElementTree to walk XML for 'station'
root= (etree.parse(noaaIndexXML)).getroot()
listStations = root.findall('station')

#Findall WA stations in XML document
waStations = [i for i in listStations if i.findall('state')[0].text == 'WA']

#Create a dictionary for each station
dictWa = {}
for i in waStations:
#Notice we are using the lat/lng values to create a geom.Point
dictWa[i.findall('station_id')[0].text] = {'the_geom':geom.Point(float(i.findall('longitude')[0].text),float(i.findall('latitude')[0].text)),'station_id':i.findall('station_id')[0].text,'lat':float(i.findall('latitude')[0].text), 'lng':float(i.findall('longitude')[0].text), 'xml_url': i.findall('xml_url')[0].text}

#Create a schema for weather stations
staSchema = schema.Schema('wa_stations_notemp',[('the_geom',geom.Point,Projection('epsg:4326')),('station_id',str),('lat',float),('lng',float),('xml_url',str)])

#Get a workspace
ws = Directory('/home/gregcorradini/GeoTools/geoscript_wrk/isolines/data/US_shapefiles/')

#Create a stations shapefile with our schema
staLayer = ws.create('wa_stations_notemp',schema=staSchema)

#Create a feature for each station value
counter = 1
for key in dictWa.keys():
staFeature = staLayer.schema.feature(dictWa[key],str(counter))
staLayer.add(staFeature)
counter += counter

2 comments:

  1. I'm a python newb. This is the error I get: Runtime error : global name 'urllib2' is not defined"

    ReplyDelete
  2. Fantastic blog you have here. You’ll discover me looking at your stuff often. Saved! portable guest bed

    ReplyDelete

Introducing GeoScript

GeoScript adds geo capabilities to dynamic scripting languages such as JavaScript, Python, Scala and Groovy.