In [1]:
import sys, os
import urllib2, httplib

%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

import numpy as np
import pandas as pd

from IPython.display import clear_output

Define wrappers around Google Maps Static API


In [75]:
def construct_googlemaps_url_request(center=None, zoom=None, imgsize=(500,500), \
                                     maptype="roadmap", apiKey="", imgformat="jpeg"):
    request =  "http://maps.google.com/maps/api/staticmap?" # base URL, append query params, separated by &
    if center is not None:
        request += "center=%s&"%center.replace(" ","+")
    if zoom is not None:
        request += "zoom=%d&"%zoom  # zoom 0 (all of the world scale ) to 22 (single buildings scale)
    if apiKey is not None:
        request += "key=%s&"%apiKey
    request += "size=%dx%d&"%imgsize  # tuple of ints, up to 640 by 640
    request += "format=%s&"%imgformat
    request += "maptype=%s&sensor=false"%maptype  # roadmap, satellite, hybrid, terrain
    return request

In [48]:
url = construct_googlemaps_url_request(center="Berkeley, CA")
url


Out[48]:
'http://maps.google.com/maps/api/staticmap?center=Berkeley,+CA&size=500x500&format=jpeg&maptype=roadmap&sensor=false'

In [78]:
import urllib
import cStringIO 
import Image

def get_static_google_map(request, filename=None):  
    if filename is not None:
        urllib.urlretrieve(request, filename) 
    else:
        web_sock = urllib.urlopen(request)
        imgdata = cStringIO.StringIO(web_sock.read()) # constructs a StringIO holding the image
        try:
            img = Image.open(imgdata)
        except IOError:
            print "IOError:", imgdata.read() # print error (or it may return a image showing the error"
            return None
        else:
            return np.asarray(img.convert("RGB"))

In [95]:
url = construct_googlemaps_url_request(center="Berkeley, CA", maptype="satellite", zoom=19)
img = get_static_google_map(url)

In [96]:
plt.figure(figsize=(7,7))
plt.imshow(img)


Out[96]:
<matplotlib.image.AxesImage at 0x7f93f8817990>

Get images for the Prop 39 schools


In [66]:
sites_df = pd.read_csv("/home/ubuntu/data/prop39/site_information.csv", \
                       converters={'Site CDS Code':str, 'Site ZIP Code':str})
sites_df.head()


Out[66]:
Site CDS Code Site Name Site City Site Mailing Address Site ZIP Code lat lon
0 1100170000000 Burke Center Hayward 313 W.Winton Ave, Hayward, CA 94544 94544 37.658469 -122.098358
1 1611196090054 Lincoln Middle School Alameda 1250 Fernside , Alameda, CA 94501 94501 37.751768 -122.232073
2 1611190132878 Encinal High School Alameda 210 Cental Ave, Alameda, CA 94501 94501 37.772765 -122.289009
3 1611196110779 Bay Farm Elementary School Alameda 200 Aughinbaugh Way , Alameda, CA 94502 94502 37.744121 -122.251922
4 1611196090005 Donald Lum Elemenary School Alameda 1801 Sandcreek Way, Alameda, CA 94501 94501 37.761699 -122.260174

In [84]:
locations = dict(zip(sites_df['Site CDS Code'].values,
                 map(lambda x, y: "%2.6f,%2.6f"%(x,y), sites_df['lat'].values, sites_df['lon'].values)))

In [97]:
myAPIKey   = "AIzaSyAmgXPgd-Db8HD_juxtPf_4nricPBdcOrw"
myOutPath  = "/home/ubuntu/data/prop39/images/"
zoomLevels = [17, 18, 19]

In [90]:
url = construct_googlemaps_url_request(center=locations.values()[0], maptype="satellite", zoom=18, apiKey=myAPIKey)
img = get_static_google_map(url)
plt.figure(figsize=(7,7))
plt.imshow(img)


Out[90]:
<matplotlib.image.AxesImage at 0x7f93f8a8af50>

In [100]:
url = construct_googlemaps_url_request(center=locations.values()[0], maptype="satellite", zoom=18, apiKey=myAPIKey)
img = get_static_google_map(url, filename=myOutPath+"/%s.jpg"%locations.keys()[0])

In [102]:
if not os.path.exists(myOutPath):
    os.makedirs(myOutPath)
for zoom in zoomLevels:
    curDir = myOutPath + "/zoom%s/"%zoom
    if not os.path.exists(curDir):
        os.makedirs(curDir)

In [117]:
for i,row in sites_df.iloc[2837:].iterrows():
    clear_output(wait=True)
    siteId   = row['Site CDS Code']
    siteName = row['Site Name']
    if type(siteName) == str:
        siteName = siteName.replace(" ", "").replace(" ", "").replace(".","").replace("/","")
    else:
        siteName = "NONE"
    loc = "%2.6f,%2.6f"%(row['lat'], row['lon'])
    for zoom in zoomLevels:
        filename = filename=myOutPath + "/zoom%s/%s_%s_z%d.jpg"%(zoom, siteId, siteName, zoom)
        url = construct_googlemaps_url_request(center=loc, maptype="satellite", zoom=zoom, apiKey=myAPIKey)
        get_static_google_map(url, filename)
        print "%d/%d : %s (zoom: %d)"%(i, len(sites_df), siteName, zoom)


3151/3152 : ProvisionalAcceleratedLearningAcademy (zoom: 17)
3151/3152 : ProvisionalAcceleratedLearningAcademy (zoom: 18)
3151/3152 : ProvisionalAcceleratedLearningAcademy (zoom: 19)

In [115]:
i


Out[115]:
2837

In [116]:
row['Site Name']


Out[116]:
nan

In [ ]: