# DyingLoveGrape.

## Part 4, Section 3: The Google Maps API.

### Python and the Google Map API.

(Last Update: .)

In order to create lots and lots of markers for our google map, we need to utilize standard programming techniques like the For loop. We'll use Python to create an HTML file with all the stuff we want on it.

#### Two Important Python Commands.

We know almost everything that we'd need to have Python create an HTML file for us except for two important things: how to save multiple lines of text in a string, and how to write to a file. Both are easy, so we cover them here.

First, start up Spyder and open up a new file.

Suppose we have a bunch of lines of text like this:

<html>
<body>
<p>It works!</p>
</body>
</html>


which look suspiciously like HTML code. Suppose we want to save this to a variable in Python. The easiest way is to use three apostrophe marks at the beginning and end, and saving it as a variable that way:

variable1 = '''<html>
<body>
<p>It works!</p>
</body>
</html>'''


You can also use three quote marks for the same effect:

variable1 = """<html>
<body>
<p>It works!</p>
</body>
</html>"""


Note that if you only use one quote mark or one apostrophe, Python will whine at you if the string spans more than one line, like our code above does. Print our our variable1 here to make sure it does, in fact, spit out more than one line.

Suppose, now, that we want to write the variable out to some file. In order to do this we need a few things: the directory of the file, the file name, and the variable or strings to put into the file. We then use the open() command. We put in a string made up of the file name with its directory and then the string 'w+' which means "we can write to this file, and we create it if it doesn't exist." For example, in Windows, I would do the following:

f = open("C:\test5.html", 'w+')


If I had another Operating System, I'd have a different directory that I'd put in with the file name. Either way, this will save the variable f as a file-type object which we can write to.

To write to a file, we use the command .write() on a file-object. It looks like this:

f.write("whatever you want")


Where the string inside could be another string, a variable, or whatever you want to write to the file.

When you're done writing and reading from a file, we use the .close() command on the file-object to tell the program we don't need it any longer. It's always nice to close a file when you're done with it. We'll see an example of this below.

Let's write the variable above to a file. Your code will look something like this:

variable1 = """<html>
<body>
<p>It works!</p>
</body>
</html>"""

f = open("C:\test5.html", 'w+')
f.write(variable1)

f.close()


Of course, replace the file directory with your directory here. Notice that we've closed the file at the end as well. Run this code and then look for the file: it should be in whatever directory you've defined. Moreover, since we've called it an .html file, you should be able to open it in a browser! Do so: you should see the text "It works!". [We could theoretically open this file in the browser right in Python using webbrowser (how?).]

#### What just happened here?

So, we saved HTML code as a string variable in Python, then had it write that string into a new file. We saved that file as an HTML file, so any HTML code is read by the browser. In essence, we wrote instructions in our string variable, then told Python to save those instructions in an HTML file which a browser will read and understand. This is an extremely powerful idea. Let's try to investigate this a bit more.

#### A Bit More Python for Creating HTML...

Before we begin: in HTML when we want to start a new paragraph or line we have to put text between two tags called paragraph tags. All text in a paragraph in HTML will look like this in the code:

<p> all the text goes here. <p>
<p> here's another line of text. <p>
<p> and another line...<p>


First, there's a lot of HTML in our bare-bones file that we don't need to worry about. Let's save some of it as variables.

intro = """<html>
<body>
"""


and also,

ending = """</body>
</html>
"""


If you're not sure why we're doing this, you may want to look at some HTML tutorials. Essentially, we're splitting this up so we can focus on the main part: the body. Everything we put between intro and ending will be visible on the main part of the webpage and, for right now, that's the most important part for us. So when we write our main code, it will look something like this:

f = open("C:\test6.html", 'w+')
f.write(intro)

(here, we can tell it to write whatever
we'd like in the body of the HTML document)

f.write(ending)
f.close()


For example, let's make a program that writes out the numbers 0 through 9 on new lines. This will be a bit strange if you've not seen this sort of thing before, so we'll take it slow. The code we'd like to have (between intro and ending) is the following:

<p>0</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>


This is a lot of writing, and it's not something we'd like to copy and paste if we had to do it for, say, a million numbers instead of 9. Instead, let's be smart. What usually would let us print out the numbers 0 through 9? The For loop, of course! Here's how such a loop would be constructed:

for i in range(10):
print "<p>" + str(i) + "</p>"


Notice that this will print out exact what we had before. Let's just look at the second like for a second. It says to print out the string "<p>" and then we add str(i) to this and then add on "</p>"; we want i to be a string so that we can concatinate it with the other two strings here (for example, try to use i in place of str(i) and see what happens!).

Of course, the print command does not print this out to the file. We have to use the write command for that. Our code, in total, should look like this:

intro = """<html>
<body>
"""

ending = """</body>
</html>
"""

f.write(intro)

for i in range(10):
f.write("<p>" + str(i) + "</p>")

f.write(ending)
f.close()


Running the program will produce the numbers 0 to 9, each on a new line. Of course, there's dozens of other ways to accomplish this, but for now this works.

Now let's say we want to have our page print out "Hello, " and then a name that you've saved as a variable. This is pretty easy given what we already know. We can do it right after the f.write(intro), and it will look like this:

name = "Jose"
f.write("<p>Hello, " + str(name) + "</p>")


This creates the opening paragraph tag, then inputs the variable which corresponds to a name, then puts in the ending paragraph tag.

The last thing I'll mention here is the If statement, which may come in handy soon. Suppose you wanted to say, "I like that name!" on the page but only if the person's name was James. We could write this directly after our previous code like this:

name = "Jose"
f.write("<p>Hello, " + str(name) + "</p>")

if name == "James":
f.write("<p>I like that name!</p>")


Again, notice the opening and closing paragraph tags. Try running this: you shouldn't see the "I like that name!" text. Now, try to change the name variable to "James". If you run the code again, you should see, "I like that name!". For reference, or if you're having some trouble, your entire code should look something like this.

#### The Many Markers Problem.

[Note, this is a bit more difficult than the previous parts. Not much more is needed in terms of know-how, but it's a lot to digest. Go through it slowly.]

Here's the problem. Suppose we have the following list of coordinates:

coord_list = ['(41.75158437309602, -87.56395118349755)', '(41.76873834225119, -87.66376561279299)', '(41.879779869678096, -87.62757244447276)', '(41.777554503599184, -87.60448994602419)', '(41.77841038321265, -87.65553686421336)', '(41.746615330695995, -87.66262135600563)', '(41.86707794697255, -87.71641921797745)', '(41.94676460304652, -87.70319753887105)', '(41.896792558131594, -87.62775981000189)']

These coordinates, by the way, come from Chicago Crime data so they're all centered around the Chicago area. Suppose we want to put a marker on our map for each of these points. Well. How do we do it?

Let's open up a new Python file in Spyder and start out like we did our other file, making an intro and an ending part. This is going to be a bit different than the previous section since, for the most part, we will be editing javascript and not HTML, but you'll see that the techniques are essentially the same. Copying and pasting from simple markers (again, remembering to change the stylesheet link as in the last part) we note that the only things we need to change are the center of the map, the variables, and the markers. Everything else will stay the same. Hence, our intro and ending will look like this. At first glance, this will look pretty intimidating, but don't be fooled: most of it is just looking at the raw HTML + Javascript and seeing what we need to change and just making the rest a long string. For example, here we just needed to change the center, the variables, and the markers, so we cut up the text from the beginning until right before we define variables, then from the end of the variables until before we input the center, then from after the center until we need to make the markers, and finally from the end of the markers until the end of the document.

Whew. Okay. Now, we need to write some code. Let's say we want our variables to be called center_point and we want that to be around (41.7, -87.5). We would like to write the Javascript for this and stick it between intro and after_variables. We can do it like this:

f.write(intro)

f.write("var center_map = new google.maps.LatLng(41.7, -87.5);")

f.write(after_variables)


That's the easy one. Now we have to make variables for all of the values in that list above that we opened the section with! We will use a little trick here. It's a bit easier to explain after we write it out, so let's just put it down here first:

f.write(intro)

f.write("var center_map = new google.maps.LatLng(41.7, -87.5);")

for i in range(len(coord_list)):
f.write("var point" + str(i) + " = new google.maps.LatLng" + coord_list[i] + ";")
f.write("\n")

f.write(after_variables)


Let's go through the new part line-by-line. The first line is a for loop, but it's saying, "For each number $i$ in the range of 0 up until the length of coord_list,..." This is a standard way to cycle through each element in a list and assign it a unique number. The next line writes a lot of things. The first $i$ value will be 0, so it will write the line

var point0 = new google.maps.LatLng(41.75158437309602, -87.56395118349755);


Notice that this names the variable point0 since $i = 0$, and it returned coord_list[0]$which is the first element in coord_list. The second value of$i\$ will be 1, so it will write the line

var point1 = new google.maps.LatLng(41.76873834225119, -87.66376561279299);


and so on. This will cycle through all of the coordinates in the list, and it will assign them a unique variable name. The f.write("\n") part simply creates a newline (the \n means "newline") after each variable which increases readability but is not strictly necessary.

We have all of our variables, so we now write the center variable in:

f.write(intro)

f.write("var center_map = new google.maps.LatLng(41.7, -87.5);")

for i in range(len(coord_list)):
f.write("var point" + str(i) + " = new google.maps.LatLng" + coord_list[i] + ";")
f.write("\n")

f.write(after_variables)

f.write("center_map")

f.write(after_center)


This will write in the variable center_map and then it will write in all of the stuff that was defined in after_center.

The last thing we need to do is to create the markers. After this, we will be done. Our program (without all of the variables and such at the top, as in here) will look like this:

f.write(intro)

f.write("var center_map = new google.maps.LatLng(41.7, -87.5);")

for i in range(len(coord_list)):
f.write("var point" + str(i) + " = new google.maps.LatLng" + coord_list[i] + ";")
f.write("\n")

f.write(after_variables)

f.write("center_map")

f.write(after_center)

# PUT IN THE MARKERS CODE HERE

f.write(ending)


When we fill in the markers code, we can run the file and (hopefully!) we will have a nice map with nice markers. The marker code is essentially the same as the variables code. We want each little piece to look like this:

var marker1 = new google.maps.Marker({position: point1, map: map, title: ''});


The only things we need to change are the 1's here, and we need it to cycle through each of our values. Another For loop will do the job! Here's how we'd code it:

for j in range(len(coord_list)):
f.write("var marker" + str(j) + " = new google.maps.Marker({position: point" + str(j) + ", map: map, title: ''});")
f.write("\n")


This has the same reasoning as the variables code. It should write out all of your markers and name them appropriatetly.

#### Whew.

At the end of the day, your code should look like this (remember, you need to put in your own directory for the html file if you copy+paste it). Note that when you run this, you should get a map with a bunch of markers. Notice that we can make minor tweaks to the code now if we'd like: for example, it's way too zoomed out for my tastes, so I can go up to the part above in the code that has zoom: 4, (in the variable after_variables) and change it to something else, like zoom: 10, which will be more zoomed in. I may also want to fix my center at some point; maybe I could take an average of the coordinates, or maybe I would center it on some important landmark. These are minor tweaks that could be made, but the heavy lifting is done.

If you've completed this, congratulations: you've used python to create an HTML document and, moreover, one which calls an API and maps a bunch of coordinates. Fifty years ago, this would have been a mad-man's dream; these days, it's just a nice way to display data!

 ⇐ Back to 4.2 Home Onwards to 4.4 ⇒