[GIS] Get lat-long of US cities and plot them on a map using matplotlib and basemap

geopymatplotlib-basemap

I am hosting a conference and want to show a map of where the attendees have arrived from. I have an input file with the names of the cities. I would like to put a dot on each city, and have the size of the dot be proportional to the number of attendees. My input looks like this:

Chicago 10
Philadelphia 20
New York 5 
San Francisco 25

I would like to do this with Python, which I believe means I should be using matplotlib and basemap. I have found sample code that has shapefiles for the US, but it's not clear to me how to get the lat/lon data US cities.

Do I have to implement this all from scratch?

Best Answer

I was able to use the API to put together the program I wanted. Here it is:

# Draw the locations of cities on a map of the US

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from geopy.geocoders import Nominatim
import math

cities = [["Chicago",10],
          ["Boston",10],
          ["New York",5],
          ["San Francisco",25]]
scale = 5

map = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
        projection='lcc',lat_1=32,lat_2=45,lon_0=-95)

# load the shapefile, use the name 'states'
map.readshapefile('st99_d00', name='states', drawbounds=True)

# Get the location of each city and plot it
geolocator = Nominatim()
for (city,count) in cities:
    loc = geolocator.geocode(city)
    x, y = map(loc.longitude, loc.latitude)
    map.plot(x,y,marker='o',color='Red',markersize=int(math.sqrt(count))*scale)
plt.show()

And here is the result: enter image description here