Google Maps provides an excellent and powerful mapping solution with some complex features whilst maintaining high usability and a fast user interface. Through the JavaScript API Google have exposed a large portion of the functionality of their maps and data for use in websites and web applications (all of which must comply with their Terms of Use). It may sound difficult but it doesn’t have to be. In fact it is quite easy to produce some quite sophisticated behaviour with relatively little code.
In this series I hope to demonstrate how to build several increasingly complex mapping applications that could have practical uses in a website or application. At the end of each part I will give some ideas for how I think the example could be adapted to a real-life situation. As the examples get more advanced the number of possible applications will increase but so also will the amount of work required to change my code to achieve a specific purpose. I hope to demonstrate to tools and techniques you might need in making these changes. So, of we go!
In the first example I will show how to create a very simple map that can be displayed on a web page with a pin marking a particular point.
Prerequisites
For this part of the tutorial you will need a basic knowledge of HTML, CSS and JavaScript and some web space but not a lot else. You won’t even need any server-side scripting!
Step 1 – Getting a Google API Key
The first step is to obtain a Google API key. This will be required for any Google Maps application that you create and is tied to the domain from which the requests to the API are made. This may mean that you need separate API keys if your development domain is different to your live domain. This is not really a problem however as it is really simple to obtain a key.
Simply go to the sign-up page, read the Terms of Use (or more likely the summary as the full document is rather dull), check the box confirming you understand the blurb, enter your site URL and generate the key.
The next page will give you your key (a really long string of letters and numbers) as well as a snippet of code to get you started. Ignore this for now as we will be recreating something similar in a moment but with more explanation along the way. If you forget your key, don’t worry as following this procedure again should result in exactly the same key as long as domain is the same.
Step 2 – Displaying a Map
Okay, that’s the boring bit over. Now for something more interesting – let’s get a map on the screen. Firstly create a simple (X)HTML file (I’ll assume you know how to do this) and add an empty div element to the body as below.
<body>
<div id="map"></div>
</body>
Make sure you don’t forget the id attribute as we’ll be using it in a moment.
Next, you’ll need to load in the API file. Add the following code to the HTML head tag replacing the key for this site with the key for yours.
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAv5cMnGZ5zeb1SlRlW91GkBStkTdrHPl7LrMl77V0klQxRUcDRBSy-WJLTWS8O7_n3a6dBXQ0xp7Jqg" type="text/javascript"></script>
Now that’s the preparation done so we can add the map itself. Create a new JavaScript file called map.js in a directory called js and add the lines
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(0, 0), 1);
}
}
window.onload = load;
window.onunload = GUnload;
So what’s going on here? Well the load() function is the bit doing all the magic and is creating a new Google Map object (if the browser can display it) and attaching it to our map div. The centre point of the map is set to longitude 0 and latitude 0 which is the point on the equator on the Prime Meridian (which runs through Greenwich). The last argument sets the zoom level of the map which is set to the minimum value to display a world map. We will change this centre point and zoom level later. We attach this function to execute when the page is loaded so the map gets displayed as soon as the user visits the page.
The GUnload() call destroys any Google JavaScript objects left around when the user navigates away from the page. This is important as in some browsers those objects would stay in memory until the whole browser is closed unless explicitly destroyed.
Okay, just a few more bits left to get the map on the screen. Firstly you will need to load in your newly created JavaScript file into the HTML page.
<script src="js/map.js" type="text/javascript"></script>
You may be wondering why I’ve separated the JavaScript into another file whereas the Google example has it all in the one HTML file. It is good practice to separate markup (HTML), behaviour (JavaScript) and presentation (CSS) into different ‘layers’ or groups of files as it helps separate your code into more maintainable and readable chunks. It also means that browsers can cache your JavaScript and CSS files independently and therefore decrease loading times. For a further discussion into these techniques see Understanding Progressive Enhancement from A List Apart or the Wikipedia article on progressive enhancement.
We need to set the size of the map on the page otherwise it will not display properly. To do this, create a CSS file called styles.css in a new directory called css. Insert the following code.
#map {
width: 500px;
height: 300px;
}
Now link the style to your HTML page by adding
<link href="css/styles.css" type="text/css" rel="stylesheet" media="screen, projection" />
to the head of the document.
If you now open your HTML page in a web browser you should see a lovely world map displayed on the page.
Step 3 - Centering the Map
That's the hard work done now lets change where the map is focused. Google Maps requires location information to be passed to it in terms of its longitude and latitude. Unless you think in these terms you will need to convert an address, location or postcode into this format in order to use it in a Google Maps application. The process of converting an address or other human readable location into its longitude and latitude is called geocoding. We will discuss this topic in a later tutorial but for now we will use the Google's own Maps application to do the work for us.
Go to Google Maps and search for the location you want to be at the centre of your map. Check that the map is centred around the correct point and that the marker is pointing to the right place. Now, right click on the marker and select the option 'Clear search results'. The marker will disappear but the map should stay centered on the same place. Now go to the top right and click 'Send'. A box will pop up containing a link. The longitude and latitude are in the 'll' fragment of the url. This is the data you will need.
For example, I searched for Downing Street, London and the URL I have is
http://maps.google.co.uk/maps?hl=en&ie=UTF8&ll=51.503093,-0.128124
&spn=0.010205,0.027895&z=16
I have highlighted the relevent fragment. In this case the longitude is 51.503093 and the latitude is -0.128124.
With these values we need to add a few lines to the beginning of the map.js file.
var latitude = -0.128124.;
var longitude = 51.503093;
var zoom = 13;
Now alter the script that sets the centre location to the following.
var location = new GLatLng(latitude, longitude);
map.setCenter(location, zoom);
Now when you load the map it should be centred around the point you specified.
Step 4 - Adding a Marker
Adding a marker is very simple. Just add the following code to your JavaScript file at the end of the load() function. This will add a marker at the same location as the map is centered.
var marker = new GMarker(location);
map.addOverlay(marker);
Load up your map in your browser and you should see you map focused on and marking the location you specified. Magic.
As you can see the amount of code involved in this is quite small considering the visual complexity of the effect. The Google Maps API allows you to tell it what you want it to do in simple terms while it does all the hard work in the background.
This example map would be perfect on a company website to show the location of an office or shop or simply to point out a landmark or a place you have visited. A picture (or map) is worth a thousand words! In future tutorials we will look at more advanced techniques like information bubbles, multiple points, interacting with the server and geocoding.