Map Visualization
import Image, urllib, json
from pylab import *
import numpy as np
from cStringIO import StringIO
import matplotlib.cm as cm
The following codes retrieve a map of Tempe from Google using three parameters: city center, zooming scale, and figure size. The latitude and longitude of world cities can be found here.
def Gmap(centerLat,centerLon,zoom,size,night,exportAddress):
url = 'http://maps.googleapis.com/maps/api/staticmap?sensor=false'\
+'&size='+str(size)+'x'+str(size)+'¢er='+str(centerLat)+','\
+str(centerLon)+'&zoom='+str(zoom)+'&scale=2&maptype=terrain'
if night == True:
url = url+'&style=feature:all|element:all|saturation:-100|lightness:-70'
buffer = StringIO(urllib.urlopen(url).read())
image = Image.open(buffer)
if exportAddress:
image.save(exportAddress)
else:
image.show()
clat,clon,zoom,size = 33.42551,-111.940005,13,640
Gmap(clat,clon,zoom,size,False,'/Users/csid/Desktop/tempe.png')
We obtain a static map:
We import the Arizona open dataset released by Yelp! to find the location of restaurants
# read Yelp! data
f = open('/Users/csid/Documents/bigdata/yelp/yelp_academic_dataset_business.json')
d = [json.loads(i) for i in f]
e = {}
for i in d:
if i['city']=='Tempe' and 'Restaurants' in i['categories']:
e[i['name']] = [i['latitude'],i['longitude'],i['stars']]
We also need to define the following function to convert the longitudes and latitudes to positions on the map. The methods for converting latitude and longtitude of locations into the coordinates of pixels on a static Google map are introduced in here, here, and here.
def latLonToPixelXY(latitude,longitude,zoomScale):
mapWidth = 256*2**zoomScale+0.0
mapHeight = 256*2**zoomScale+0.0
# get x value
x = (longitude+180)*(mapWidth/360)
# convert from degrees to radians
latRad = latitude*np.pi/180
# get y value
mercN = np.log(np.tan((np.pi/4)+(latRad/2)))
y = (mapHeight/2)-(mapWidth*mercN/(2*np.pi))
return x,y
# mapping data points in the Yelp! dataset
cx, cy = latLonToPixelXY(clat,clon,zoom)
for i in e:
lat,lon,score = e[i]
x, y = latLonToPixelXY(lat,lon,zoom)
nx, ny = 640*2/2 + x - cx, 640*2/2 - (y - cy)
e[i] = [nx,ny,score]
# save data for plotdevice
with open('/Users/csid/Desktop/tempeRest.text','wb') as f:
for i in e:
try:
x,y,score = map(str,e[i])
f.write(i+'\t'+x+'\t'+y+'\t'+score+'\n')
except:
pass
Now we can plot the map on which restaurants are marked:
fig = plt.figure(figsize=(8, 8),facecolor='white')
cm = plt.cm.get_cmap('rainbow')
im = np.flipud(plt.imread('/Users/csid/Desktop/tempe.png'))
ax = fig.add_subplot(111)
ax.imshow(im, origin='lower')
plt.axis('off')
x,y,score = np.array(e.values()).T
fig1 = ax.scatter(x,y,s=score**2,c=score,cmap=cm,alpha=0.7)
ax.set_xlim(0,640*2)
ax.set_ylim(0,640*2)
plt.colorbar(fig1, ax=ax,shrink=.7, pad=0.05, aspect=20)
plt.savefig('/Users/csid/Desktop/yelpmap.png',bbox_inches="tight")
#plt.show()