Skip to content
ADVERTISEMENT
Sign In
  • Sections
    • News
    • Advice
    • The Review
  • Topics
    • Data
    • Diversity, Equity, & Inclusion
    • Finance & Operations
    • International
    • Leadership & Governance
    • Teaching & Learning
    • Scholarship & Research
    • Student Success
    • Technology
    • Transitions
    • The Workplace
  • Magazine
    • Current Issue
    • Special Issues
    • Podcast: College Matters from The Chronicle
  • Newsletters
  • Virtual Events
  • Ask Chron
  • Store
    • Featured Products
    • Reports
    • Data
    • Collections
    • Back Issues
  • Jobs
    • Find a Job
    • Post a Job
    • Professional Development
    • Career Resources
    • Virtual Career Fair
  • More
  • Sections
    • News
    • Advice
    • The Review
  • Topics
    • Data
    • Diversity, Equity, & Inclusion
    • Finance & Operations
    • International
    • Leadership & Governance
    • Teaching & Learning
    • Scholarship & Research
    • Student Success
    • Technology
    • Transitions
    • The Workplace
  • Magazine
    • Current Issue
    • Special Issues
    • Podcast: College Matters from The Chronicle
  • Newsletters
  • Virtual Events
  • Ask Chron
  • Store
    • Featured Products
    • Reports
    • Data
    • Collections
    • Back Issues
  • Jobs
    • Find a Job
    • Post a Job
    • Professional Development
    • Career Resources
    • Virtual Career Fair
    Upcoming Events:
    Hands-On Career Preparation
    An AI-Driven Work Force
    Alternative Pathways
Sign In
Profhacker Logo

ProfHacker

Teaching, tech, and productivity.

Working with APIs (part 3)

By Julie Meloni September 28, 2009


In the previous installments (1, 2) of this series, I talked about APIs in general and showed how data can be pulled from an API without server-side programming knowledge. In this third installment of the “Working with APIs” series we will continue to work with the Google Code developer resources and use already-created client-side code to do even more with the data that you can retrieve.


In the last installment of the series we took apart a query string and discussed how different parts of that string are variables and other parts are the values for those variables, and that when the query string is used those variables and their values are sent to a script that then produces output based on those variables and values. The primary example used was sending a query string to the Google Maps API so that it produced an image (a slice of a map, in this case) per your specifications. The map example in the previous installment used the static Google Maps API—still powerful, but lacking interactivity. The interactivity comes from using the Google Maps API with JavaScript (or Flash).


JavaScript is a client-side scripting language, meaning that JavaScript code exists within the HTML source file and is interpreted by your web browser when the source file is requested and rendered; in addition to displaying the text, images, and styles within the source file, the browser will also interpret and run any client-side code either at the time the page is loaded or when a user action invokes the code. This process differs from a server-side scripting language such as PHP, JSP, ASP, Perl, Python, Ruby and so on. With server-side scripting, code is stored and executed on the server side and output (typically HTML or other marked-up text) is sent separately to the browser, which then renders the output as a regular old web page.

But enough of that—we’ll save more of that talk for the fourth installment of this series.


The Google Maps API allows you to create map images, and adding JavaScript into the mix allows you to provide interactivity with those images. The goal here is to make you comfortable with manipulating the JavaScript code you are given, working within an example that is easy to understand (unless you’re map-challenged). Again, Google Code is not the only code out there that will allow you do manipulate APIs via query strings or JavaScript, but I am using it in this series of posts because there are a lot of code examples and tutorials available for many of the Google services (and they’re free). The same concepts of examining API documentation and working with snippets you’re given will hold true for many other APIs out there—and I’ll show you another at the end of this tutorial.


As per usual (for Google), after you sign up for an API key you can head on over to “The Hello World of Google Maps” and follow along as they explain the very basics of getting started with the Maps API and JavaScript. These basics include working with what they have given you for free, namely:

  • The code to paste in the <head> of your file that will include the Maps API JavaScript using a <script> tag.
  • The <div> element that will hold the map
  • The JavaScript function used to create a map object.
  • How to center the map on a given geographic point.
  • How the map object is initialized from <body> tag’s onload event.

In other words, what happens when they give you the following code, you put it in an HTML file and open it with your web browser:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type” content="text/html; charset=utf-8"/>
<title>Google Maps API Example with JavaScript</title>
<script src="http://maps.google.com/maps?file=api&v=2
&sensor=false&key=YOUR_KEY”
type="text/javascript"> </script>
<script type="text/javascript">
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById(“map_canvas”));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.setUIToDefault();
}
}
</script>
</head>
<body onload="initialize()” onunload="GUnload()">
<div id="map_canvas” style="width: 500px; height: 300px"></div>
</body>
</html>


What does happen is that a 500 pixel wide, 300 pixel high map centered on Palo Alto, California shows up in your browser. I will bet that if you know that 37.4419, -122.1419 are the latitude and longitude values for Palo Alto, you can read the code and figure out where the other numbers are located. I don’t mean “read the code” like these guys do (not yet, at least), but focus on the function, the <body>, and the <div> in use. The initial <script> tag, the one with the URL that includes your API key among other things, pulls in additional code libraries and information so that you don’t have to write it.


The JavaScript function that controls the output of the map is called “initialize” and begins with word “function”. So, this line:

function initialize() {

means “I am creating a function and calling it ‘initialize’ and everything after the open curly brace, until the closed curly brace, is what I want the function to do.” The first line in the function sets up a check for browser compatiblity by invoking another function called GBrowserIsCompatible() and if the check is good (the browser is compatible) then everything between this new set of curly braces will occur. Note that the GBrowserIsCompatible() function is one of a few other functions referenced in this example code that you don’t actually see. They are part of the library that is included by virtue of the first <script> tag, the one with the URL that includes your API key among other things.

The three lines inside the conditional statement (the “if”) do all the magic. Well, most of it:

var map = new GMap2(document.getElementById(“map_canvas”));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.setUIToDefault();

The first line creates a new map instance using a variable called map (var map); this is a new instance of the GMap2 object (new GMap2). Note that when the new instance is created this text sent along with it: document.getElementById(“map_canvas”)

This additional bit of information tells the GMap2 object precisely where you want the output to occur. In this case, the output will reside in some element within the document that has an ID of “map_canvas”. If you look further down the code listing you’ll see this bit of HTML: <div id=”map_canvas” style=”width: 500px; height: 300px”></div>

A-ha! This <div> element has an ID value of “map_canvas” so it must be where the map will be placed—and indeed it is. You can see that additional style properties for this <div> include the height and width; you can also put a border in here or any other style you wish. You could also provide all the styles in a style sheet entry for the “map_canvas” ID if you wanted. The point is, this bit of HTML is separate from the Google Maps API or any JavaScript code, and it is something you can control. All the code needs to know is that there is an element in the page called “map_canvas”—you can change that element ID in the JavaScript to something else, as long as that something else also exists in the HTML code. Otherwise the output of the JavaScript will have nowhere to go.


The remaining two lines initialize the new map using two pre-defined methhods: setCenter() and setUItoDefault(). The setCenter() method defines the center position of the map and the zoom level. In this instance, the center of the map is set to the result of values sent through another piece of code, GLatLang() (again, you are just using stuff already created for you). The zoom level is 13. The second line simply loads the default user interface tools—this line is the line that makes the output of this map different than the static map from the previous installment of this series. Well, that and the modification to the <body> tag that invokes the initialize function in the first place:

<body onload="initialize()” onunload="GUnload()">

The onload event simply means “when this page is loaded, run the function called initialize”—the function written and sitting there in the page as well. The function sits there until it is called, and in this case it is called automatically when the page loads. The onunload event calls the GUnload() function (not created by you, but in the Google code library) to clean up when the page is “unloaded,” also known as when you browse away from it.

Ok, enough explaining—here’s an example of a new “initialize” function:


function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById(“map_canvas”));
map.setCenter(new GLatLng(34.943855,-81.928657), 8);
map.setUIToDefault();
// Create a marker icon
var unicorn = new GIcon();
unicorn.image = “http://www.academicsandbox.com/misc/unicorn.gif";
unicorn.iconSize = new GSize(85, 100);
unicorn.iconAnchor = new GPoint(-15, 15);
// Set up a GMarkerOptions object
markerOptions = { icon:unicorn };
// Set up the point
var point = new GLatLng(34.943855,-81.928657);
map.addOverlay(new GMarker(point, markerOptions));
}
}

All I have done is:

  • change the latitude/longitude for the center of the map
  • created a new marker icon called “unicorn”
  • told the API where to get the icon
  • told the API the size of the icon
  • told the API where to place the icon relative to the location of the point
  • created a marker object for later reference
  • set up the point using latitude/longitude values and placing the marker as an overlay on the map


Because I can’t run this code within the WordPress post (the editor mangles the code), I’ve put the page in an iframe so that you can see what it looks like and can interact with it. Go ahead—move the map around and use the UI controls that make this different than a static map. [if you can’t see the iframe, access the page directly.]


Loading&#8230;
Thus ends today’s example of how you can work with APIs and additional libraries already coded for you to produce a little more interactivity with not very much effort. Ok, so perhaps overlaying a unicorn onto a map isn’t your cup of tea. The greater point I’m trying to make is that if you start looking more closely at some of the widgets you might already be copying and pasting into your pages, you can start to see how those too are often just variables and values that you can modify, which are sent to an API using a framework already provided for you.


For instance, some of you might have used the Twitter Search Widget Generator to produce a box of scrolling search results that you then embedded into your web content. That wizard simply fills out the values of predefined variables for you, like so:


new TWTR.Widget({
search: ‘SOME SEARCH GOES HERE’,
id: ‘SOME ID GOES HERE’,
loop: TRUE OR FALSE,
title: ‘SOME TITLE GOES HERE’,
subject: ‘SOME SUBJECT GOES HERE’,
width: SOME WIDTH,
height: SOME HEIGHT,
theme: {
shell: {
background: ‘SOME HEX CODE’,
color: ‘SOME HEX CODE’
},
tweets: {
background: ‘SOME HEX CODE’,
color: ‘SOME HEX CODE’,
links: ‘SOME HEX CODE’
}
}
}).render().start();

So, if I wanted to search for mentions of Prof. Hacker and wanted to color up the widget in some fashion, I might use:


new TWTR.Widget({
search: ‘profhacker OR “Prof. Hacker”’,
id: ‘twtr-search-widget2',
loop: true,
title: ‘What people are saying about...’,
subject: ‘Prof. Hacker’,
width: 450,
height: 125,
theme: {
shell: {
background: '#7fae52',
color: '#ffffff’
},
tweets: {
background: '#ffffff’,
color: '#444444',
links: '#3b1a4a’
}
}
}).render().start();


If I then added links to the additional style sheet and libraries, and provided an appropriately-named element for the widget to be placed, I’d get something [the move to the Chronicle of Higher Education means I can’t run this in their system.]


Moving from just working with query strings to working with coding frameworks isn’t that big of a leap—there are still variables you should look up in the API documentation of your service of choice, and values you have to assign to those variables, but still most of the hard work is done by code already provided for you. In the next installment of this series I’ll show you some nifty tricks that involve server-side programming—the stuff geeks are made of.

To continue reading for FREE, please sign in.

Sign In

Or subscribe now to read with unlimited access for as low as $10/month.

Don’t have an account? Sign up now.

A free account provides you access to a limited number of free articles each month, plus newsletters, job postings, salary data, and exclusive store discounts.

Sign Up



In the previous installments (1, 2) of this series, I talked about APIs in general and showed how data can be pulled from an API without server-side programming knowledge. In this third installment of the “Working with APIs” series we will continue to work with the Google Code developer resources and use already-created client-side code to do even more with the data that you can retrieve.


In the last installment of the series we took apart a query string and discussed how different parts of that string are variables and other parts are the values for those variables, and that when the query string is used those variables and their values are sent to a script that then produces output based on those variables and values. The primary example used was sending a query string to the Google Maps API so that it produced an image (a slice of a map, in this case) per your specifications. The map example in the previous installment used the static Google Maps API—still powerful, but lacking interactivity. The interactivity comes from using the Google Maps API with JavaScript (or Flash).


JavaScript is a client-side scripting language, meaning that JavaScript code exists within the HTML source file and is interpreted by your web browser when the source file is requested and rendered; in addition to displaying the text, images, and styles within the source file, the browser will also interpret and run any client-side code either at the time the page is loaded or when a user action invokes the code. This process differs from a server-side scripting language such as PHP, JSP, ASP, Perl, Python, Ruby and so on. With server-side scripting, code is stored and executed on the server side and output (typically HTML or other marked-up text) is sent separately to the browser, which then renders the output as a regular old web page.

But enough of that—we’ll save more of that talk for the fourth installment of this series.


The Google Maps API allows you to create map images, and adding JavaScript into the mix allows you to provide interactivity with those images. The goal here is to make you comfortable with manipulating the JavaScript code you are given, working within an example that is easy to understand (unless you’re map-challenged). Again, Google Code is not the only code out there that will allow you do manipulate APIs via query strings or JavaScript, but I am using it in this series of posts because there are a lot of code examples and tutorials available for many of the Google services (and they’re free). The same concepts of examining API documentation and working with snippets you’re given will hold true for many other APIs out there—and I’ll show you another at the end of this tutorial.


As per usual (for Google), after you sign up for an API key you can head on over to “The Hello World of Google Maps” and follow along as they explain the very basics of getting started with the Maps API and JavaScript. These basics include working with what they have given you for free, namely:

  • The code to paste in the <head> of your file that will include the Maps API JavaScript using a <script> tag.
  • The <div> element that will hold the map
  • The JavaScript function used to create a map object.
  • How to center the map on a given geographic point.
  • How the map object is initialized from <body> tag’s onload event.

In other words, what happens when they give you the following code, you put it in an HTML file and open it with your web browser:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type” content="text/html; charset=utf-8"/>
<title>Google Maps API Example with JavaScript</title>
<script src="http://maps.google.com/maps?file=api&v=2
&sensor=false&key=YOUR_KEY”
type="text/javascript"> </script>
<script type="text/javascript">
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById(“map_canvas”));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.setUIToDefault();
}
}
</script>
</head>
<body onload="initialize()” onunload="GUnload()">
<div id="map_canvas” style="width: 500px; height: 300px"></div>
</body>
</html>


What does happen is that a 500 pixel wide, 300 pixel high map centered on Palo Alto, California shows up in your browser. I will bet that if you know that 37.4419, -122.1419 are the latitude and longitude values for Palo Alto, you can read the code and figure out where the other numbers are located. I don’t mean “read the code” like these guys do (not yet, at least), but focus on the function, the <body>, and the <div> in use. The initial <script> tag, the one with the URL that includes your API key among other things, pulls in additional code libraries and information so that you don’t have to write it.


The JavaScript function that controls the output of the map is called “initialize” and begins with word “function”. So, this line:

function initialize() {

means “I am creating a function and calling it ‘initialize’ and everything after the open curly brace, until the closed curly brace, is what I want the function to do.” The first line in the function sets up a check for browser compatiblity by invoking another function called GBrowserIsCompatible() and if the check is good (the browser is compatible) then everything between this new set of curly braces will occur. Note that the GBrowserIsCompatible() function is one of a few other functions referenced in this example code that you don’t actually see. They are part of the library that is included by virtue of the first <script> tag, the one with the URL that includes your API key among other things.

The three lines inside the conditional statement (the “if”) do all the magic. Well, most of it:

var map = new GMap2(document.getElementById(“map_canvas”));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.setUIToDefault();

The first line creates a new map instance using a variable called map (var map); this is a new instance of the GMap2 object (new GMap2). Note that when the new instance is created this text sent along with it: document.getElementById(“map_canvas”)

This additional bit of information tells the GMap2 object precisely where you want the output to occur. In this case, the output will reside in some element within the document that has an ID of “map_canvas”. If you look further down the code listing you’ll see this bit of HTML: <div id=”map_canvas” style=”width: 500px; height: 300px”></div>

A-ha! This <div> element has an ID value of “map_canvas” so it must be where the map will be placed—and indeed it is. You can see that additional style properties for this <div> include the height and width; you can also put a border in here or any other style you wish. You could also provide all the styles in a style sheet entry for the “map_canvas” ID if you wanted. The point is, this bit of HTML is separate from the Google Maps API or any JavaScript code, and it is something you can control. All the code needs to know is that there is an element in the page called “map_canvas”—you can change that element ID in the JavaScript to something else, as long as that something else also exists in the HTML code. Otherwise the output of the JavaScript will have nowhere to go.


The remaining two lines initialize the new map using two pre-defined methhods: setCenter() and setUItoDefault(). The setCenter() method defines the center position of the map and the zoom level. In this instance, the center of the map is set to the result of values sent through another piece of code, GLatLang() (again, you are just using stuff already created for you). The zoom level is 13. The second line simply loads the default user interface tools—this line is the line that makes the output of this map different than the static map from the previous installment of this series. Well, that and the modification to the <body> tag that invokes the initialize function in the first place:

<body onload="initialize()” onunload="GUnload()">

The onload event simply means “when this page is loaded, run the function called initialize”—the function written and sitting there in the page as well. The function sits there until it is called, and in this case it is called automatically when the page loads. The onunload event calls the GUnload() function (not created by you, but in the Google code library) to clean up when the page is “unloaded,” also known as when you browse away from it.

Ok, enough explaining—here’s an example of a new “initialize” function:


function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById(“map_canvas”));
map.setCenter(new GLatLng(34.943855,-81.928657), 8);
map.setUIToDefault();
// Create a marker icon
var unicorn = new GIcon();
unicorn.image = “http://www.academicsandbox.com/misc/unicorn.gif";
unicorn.iconSize = new GSize(85, 100);
unicorn.iconAnchor = new GPoint(-15, 15);
// Set up a GMarkerOptions object
markerOptions = { icon:unicorn };
// Set up the point
var point = new GLatLng(34.943855,-81.928657);
map.addOverlay(new GMarker(point, markerOptions));
}
}

All I have done is:

  • change the latitude/longitude for the center of the map
  • created a new marker icon called “unicorn”
  • told the API where to get the icon
  • told the API the size of the icon
  • told the API where to place the icon relative to the location of the point
  • created a marker object for later reference
  • set up the point using latitude/longitude values and placing the marker as an overlay on the map


Because I can’t run this code within the WordPress post (the editor mangles the code), I’ve put the page in an iframe so that you can see what it looks like and can interact with it. Go ahead—move the map around and use the UI controls that make this different than a static map. [if you can’t see the iframe, access the page directly.]


Loading&#8230;
Thus ends today’s example of how you can work with APIs and additional libraries already coded for you to produce a little more interactivity with not very much effort. Ok, so perhaps overlaying a unicorn onto a map isn’t your cup of tea. The greater point I’m trying to make is that if you start looking more closely at some of the widgets you might already be copying and pasting into your pages, you can start to see how those too are often just variables and values that you can modify, which are sent to an API using a framework already provided for you.


For instance, some of you might have used the Twitter Search Widget Generator to produce a box of scrolling search results that you then embedded into your web content. That wizard simply fills out the values of predefined variables for you, like so:


new TWTR.Widget({
search: ‘SOME SEARCH GOES HERE’,
id: ‘SOME ID GOES HERE’,
loop: TRUE OR FALSE,
title: ‘SOME TITLE GOES HERE’,
subject: ‘SOME SUBJECT GOES HERE’,
width: SOME WIDTH,
height: SOME HEIGHT,
theme: {
shell: {
background: ‘SOME HEX CODE’,
color: ‘SOME HEX CODE’
},
tweets: {
background: ‘SOME HEX CODE’,
color: ‘SOME HEX CODE’,
links: ‘SOME HEX CODE’
}
}
}).render().start();

So, if I wanted to search for mentions of Prof. Hacker and wanted to color up the widget in some fashion, I might use:


new TWTR.Widget({
search: ‘profhacker OR “Prof. Hacker”’,
id: ‘twtr-search-widget2',
loop: true,
title: ‘What people are saying about...’,
subject: ‘Prof. Hacker’,
width: 450,
height: 125,
theme: {
shell: {
background: '#7fae52',
color: '#ffffff’
},
tweets: {
background: '#ffffff’,
color: '#444444',
links: '#3b1a4a’
}
}
}).render().start();


If I then added links to the additional style sheet and libraries, and provided an appropriately-named element for the widget to be placed, I’d get something [the move to the Chronicle of Higher Education means I can’t run this in their system.]


Moving from just working with query strings to working with coding frameworks isn’t that big of a leap—there are still variables you should look up in the API documentation of your service of choice, and values you have to assign to those variables, but still most of the hard work is done by code already provided for you. In the next installment of this series I’ll show you some nifty tricks that involve server-side programming—the stuff geeks are made of.

We welcome your thoughts and questions about this article. Please email the editors or submit a letter for publication.
Share
  • Twitter
  • LinkedIn
  • Facebook
  • Email
ADVERTISEMENT
ADVERTISEMENT

More News

Marva Johnson is set to take the helm of Florida A&amp;M University this summer.
Leadership & governance
‘Surprising': A DeSantis-Backed Lobbyist Is Tapped to Lead Florida A&M
Students and community members protest outside of Coffman Memorial Union at the University of Minnesota in Minneapolis, on Tuesday, April 23, 2024.
Campus Activism
One Year After the Encampments, Campuses Are Quieter and Quicker to Stop Protests
Hoover-NBERValue-0516 002 B
Diminishing Returns
Why the College Premium Is Shrinking for Low-Income Students
Harvard University
'Deeply Unsettling'
Harvard’s Battle With Trump Escalates as Research Money Is Suddenly Canceled

From The Review

Illustration showing a valedictorian speaker who's tassel is a vintage microphone
The Review | Opinion
A Graduation Speaker Gets Canceled
By Corey Robin
Illustration showing a stack of coins and a university building falling over
The Review | Opinion
Here’s What Congress’s Endowment-Tax Plan Might Cost Your College
By Phillip Levine
Photo-based illustration of a college building under an upside down baby crib
The Review | Opinion
Colleges Must Stop Infantilizing Everyone
By Gregory Conti

Upcoming Events

Ascendium_06-10-25_Plain.png
Views on College and Alternative Pathways
Coursera_06-17-25_Plain.png
AI and Microcredentials
  • Explore Content
    • Latest News
    • Newsletters
    • Letters
    • Free Reports and Guides
    • Professional Development
    • Virtual Events
    • Chronicle Store
    • Chronicle Intelligence
    • Jobs in Higher Education
    • Post a Job
  • Know The Chronicle
    • About Us
    • Vision, Mission, Values
    • DEI at The Chronicle
    • Write for Us
    • Work at The Chronicle
    • Our Reporting Process
    • Advertise With Us
    • Brand Studio
    • Accessibility Statement
  • Account and Access
    • Manage Your Account
    • Manage Newsletters
    • Individual Subscriptions
    • Group and Institutional Access
    • Subscription & Account FAQ
  • Get Support
    • Contact Us
    • Reprints & Permissions
    • User Agreement
    • Terms and Conditions
    • Privacy Policy
    • California Privacy Policy
    • Do Not Sell My Personal Information
1255 23rd Street, N.W. Washington, D.C. 20037
© 2025 The Chronicle of Higher Education
The Chronicle of Higher Education is academe’s most trusted resource for independent journalism, career development, and forward-looking intelligence. Our readers lead, teach, learn, and innovate with insights from The Chronicle.
Follow Us
  • twitter
  • instagram
  • youtube
  • facebook
  • linkedin