Introduction to JavaScript and the Google Maps API

JavaScript is a client-side (browser) programming language used with HTML and CSS to control how web pages interact with users. JavaScript is used extensively for displaying maps on web pages and providing the ability for users to navigate and query those maps.

JavaScript has a wide variety of constructs, applications and practices that takes considerable time to master at a professional level. However, there are some fundamental elements that can be learned quickly, and by the conclusion of this exercise you should be able to copy, understand, and customize simple scripts that use the Google Maps JavaScript API (Application Programming Interface).

If JavaScript is entirely new to you, and/or you find this tutorial confusing, you may wish to work through some of the W3 Schools JavaScript Tutorial to give you a firmer foundation on the basics of JavaScript.

Firefox Web Console

While JavaScript is useful and ubiquitous, it can be a frustrating language that requires persistence even for experienced users.

The Firefox browser includes developer tools, notably the Web Console that can help you diagnose problems with your JavaScript code.

A Simple Map

The following is a minimal example of a map embedded with the Google Maps JavaScript API:

Note that if you embed this map on your own web site, you will need a free Standard API Key, which you can get from the Google Maps API website. You will need Google (gmail) login credentials. You will then insert the API key as a query string on the end of the SCRIPT URL:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

The <div> element defines a division or section of the page that will be filled with a google map.

The DIV is given an id attribute with the value of map so it can be identified in the JavaScript.

The DIV also has some CSS in the style attribute that tells it to be 600 pixels wide and 400 pixels tall.

The first <script> element has a src attribute that tells it to bring in the Google Maps API JavaScript library. This library contains additional JavaScript code that does most of the work in creating a map.

The second <script> element contains our JavaScript that fills the <div> with a Google Map.

var map_parameters = { center: {lat: 47.490, lng: -117.585}, zoom: 8 };

This statement creates a variable and assigns a value to it.

This type of value is called an object. An object contains one or more named properties that are given values following a colon.

If an object contains more than one property, commas are used to separate separate property-value pairs.

This newly-created map_parameters object variable is created with two properties: the location of the center of the map and the initial zoom level for the map.

The center property is itself an object containing a latitude and longitude where the center of the map will initially be placed (in WGS 84 degrees).

var map = new google.maps.Map(document.getElementById('map'), map_parameters);

Objects can also have methods in additions to properties. Methods are specific examples of named functions that are passed a set of parameters in parenthesis and return a value of some kind.

The second map variable is created by calling the Map() method on the google.maps object. That object comes from the Google Maps API library that we loaded earlier.

The two parameters passed to this method are the map element and the map parameters object we created in the line above.

The value for the map element parameter is the output of the getElementById() method on the document object that contains all the content on a web page. The parameter to this method is the id for the desired element, in this case, the name of the <div> we are going to use for the map. The method returns an object that allows that element to be changed by the Google maps API code.

Note that in JavaScript (unlike some other programming languages like Python) each statement must be ended with a semicolon.

Also note that objects are often passed directly to functions without being assigned a name first. While this makes the code a bit more confusing to read, it is a common shortcut you will see in JavaScript examples.

var map = new google.maps.Map(document.getElementById('map'),
	{ center: {lat: 47.490, lng: -117.585}, zoom: 8 });

Adding Placemarks

This code places two placemarks on the map.

The position objects have two properties: the latitude and longitude for the placemarks, and the map that the placemarks will be placed on.

The google.maps.Marker() function takes an object with that information as its one parameter.

Events and InfoWindows

Maps often need to respond to user actions, such as mouse clicks, swiping or dragging. Those actions are referred to in JavaScript as events.

A common behavior with placemarks is to pop up an infoWindow when a placemark receives a click event.

The info variable is created with an InfoWindow object.

The addListener() method tells the API to listen for an event that occurs on an object in the document, and then call a function to handle that event. In this case, a 'click' event occurs when someone clicks on one of the markers. The addListener() method tells the API to call the marker_clicked() function when someone clicks on the specified placemark.

function marker_clicked() creates a user-defined function that contains code performed when the function is called. The this variable refers to the object that caused the function to be called.

The marker_clicked() function calls the setContent() method function for the info windo to set the text displayed in the window.

The open() method then causes the infoWindow to open on top of the marker that caused the click event, in this case indicated by the this parameter.

KML and KMZ Overlays

One of the capabilities that makes using the Google Maps API preferable to embedding an IFRAME is the ability to overlay maps, and use Google Maps as a base layer.

For an overlay you need a KML file containing the geospatial information and styling for the overlaid points, lines or polygons.

That file will be converted to tiles by Google when you first load it, so it must be located on a publicly available web server - you cannot practice with KML overlays entirely on your local hard drive. The KMZ file in this example is located on the same server as this tutorial. To create your own overlay, you should upload your KML or KMZ file to your own server.

Asynchronous Loading

Most of the examples you see on the Google Maps Javascript API Code Samples place the mapping code in a function, and then call that function asynchronously after the API library has loaded. This allows the other content page to be displayed while the library loads, so the user is not presented with a blank window for an extended period of time.

This is not necessary and makes the code a bit more difficult to read, but you should be aware that mapping examples you see on the web will commonly use tricks like this.

Google Code Samples

Google Maps Javascript API Code Samples are a good resource for learning a variety of additional simple and advanced techniques using the Google Maps JavaScript API.

The Google Maps API in WordPress

The Google Maps API can be used on WordPress pages, although some tweaks are helpful to make working with the API easier.

WordPress comes installed with filters intended to improve the appearance and security of a WordPress site, but which make use of JavaScript in general, and the Google Maps API in particular, more difficult.

One filter is wpautop which looks for blank lines in HTML and adds paragraph tags to make the blank lines into paragraph separators. This will mangle JavaScript if there are blank lines in your code to improve readability.

The other filter prevents the upload of KML or KMZ files to the media library as a security measure. This forces the use of a separate FTP program to upload these files for use as overlays.

Both of these features can be disabled by adding some PHP code to the functions.php file of your theme. To edit this file, use the editor feature from your WordPress dashboard:

Appearance -> Editor -> Theme Functions (functions.php)

Then add the following PHP code after the comments at the top of the functions.php file - which end with a */:

remove_filter('the_content', 'wpautop');
function my_myme_types($mime_types)
{
            $mime_types['kml'] = 'application/vnd.google-earth.kml+xml';
            $mime_types['kmz'] = 'application/vnd.google-earth.kmz';
            return $mime_types;
}
add_filter('upload_mimes', 'my_myme_types', 1, 1);

After making these changes, you can copy the contents of the HTML within the <body" into a WordPress page using the Text editor (not the Visual editor). For a simple map, this would be:

<div id="map" style="width:600px; height: 400px;"></div>

<script src="https://maps.googleapis.com/maps/api/js"></script>

<script>
	var map_parameters = { center: {lat: 47.490, lng: -117.585}, zoom: 8 };
	var map = new google.maps.Map(document.getElementById('map'), map_parameters);
</script>

There are a number of plugins available to make importing Google Maps easier, although the simple tweaks given above will give you the full flexibility available by using the Google Maps API directly.