/AJAX/ Working with Google Maps

10/10/2006 | Filed under Develop > AJAX

Rik Lomas shows you all the techniques you need to incorporate AJAX into your site and use the Google Maps API to best effect

Whoever would have thought that Microsoft could devise something that reignited interest in web development again and started a whole new wave of Web 2.0 sites? AJAX, which stands for Asynchronous JavaScript And XML, is a technique (rather than a technology) that exchanges small amounts of data with servers that are working behind the scene. Basically it means that web pages don’t need to be reloaded for them to receive new data. AJAX relies heavily on the XMLHttpRequest object, originally a Microsoft ActiveX object, which is used for establishing a connection between the client side and the server side.

Despite the XMLHttpRequest object being around since the dotcom boom, it’s popularity has only increased recently with the explosion of the Web 2.0 movement. AJAX is now synonymous with Web 2.0, and any new Web 2.0 site is almost expected to have some sort of AJAX. Forerunners, which skyrocketed the popularity of these new methods, include Google Suggest (labs.google.com/suggest), Writely (www.writely.com) and Flickr (www.flickr.com), but possibly the most notable of the Web 2.0 movement was Google Maps (maps.google.co.uk).

With its dragging interface and pop-up bubbles. It was a completely new way of interacting not only with maps but also with web pages. With the Google Maps’ API you can have the power of its mapping interface on your site. Many people have already used it to created mashup sites, which combine data from various sources and form it into a new way of viewing the data. For example, HousingMaps.com places Craigslist property listings on a Google map, while Chicagocrime.org (www.chicagocrime.org/map) lets you view a map of crime locations in Chicago.

Making your map

The first thing you need to do is sign up for a Google Maps API key. Without it, you can’t use Google’s API. Go to www.google.com/apis/maps and follow the instructions – they’re really simple to follow and it shouldn’t take longer than a minute or two to sign up for a key.

You can now easily set up a simple map, 700 pixels wide by 500 pixels high. Make sure it’s an HTML file and call it index.html:

<!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</title>
<script src=”http://maps.google.com/maps?file=api&amp;v=2&amp;key=YOUR_
API_KEY” type=”text/javascript”></script>
<script type=”text/javascript” src=”map.js”></script>
<link rel=”stylesheet” href=”style.css” type=”text/css” media=”all” title=”” />
</head>
<body>
<div id=”map” style=”width: 700px; height: 500px”>
<span id=”maploading”>Loading Map</span>
</div>
</body>

Now create a JavaScript file called map.js:

function load () {
var map = document.getElementById(“map”);
if (GBrowserIsCompatible()) {
var gmap = new GMap2(map);
gmap.addControl( new GSmallMapControl() );
gmap.addControl( new GMapTypeControl()) ;
gmap.addControl( new GOverviewMapControl(new GSize(100,100)) );
gmap.setCenter( new GLatLng(54.7,-4), 5 );
} else {
alert(“Sorry, your browser cannot handle the true power of Google Maps”);
}
}
window.onload = load;
window.onunload = GUnload;

The JavaScript finds the tag with the ID name ‘map’ in the HTML (line two) and, if the browser can handle Google Maps (line three), places a new map within the tag marked map in the HTML (line four). You can then add some controls to the maps, namely the control arrows in the top left (line five), a map type selector in the top right (line six), and a 100 by 100 pixel map overview in the bottom right (line seven). Then set the centre of the map to latitude 54.7 degrees and -4 degrees longitude (which is somewhere in the sea near Cumbria), with a magnification of five (line eight), and you’ll get a nice map of the UK (Fig 1).


Obviously, a map of the UK with nothing on it is a bit boring for the average visitor. Putting something on the map would be a nice idea, but you’ll need some information to put on there as well. Information with a structure would be nice, too. Most people would immediately think of XML when information with structure is talked about, but because you’re using JavaScript for this, you can use a different technology.

Introducing JSON

JSON (pronounced ‘Jason’) stands for JavaScript Object Notation and is a lightweight data format, similar to XML. The advantage that JSON has over XML when used in JavaScript is that it’s very easy to parse and traverse. Take the following XML document as an example:

<root>
<email type=”work”>rik@test.com</email>
</root>

You could have a similar JSON file such as this:

{ “root” : {
“email” : {
“type”: “work”,
“value”: “rik@test.com
}
}
}

In JavaScript, to get the ‘value’ value (which, in this case, is rik@test.com), you can just type ‘root.email.value’, which is easier than traversing an XML tree, especially when the information you want to put on your site starts to get more complicated. Also, it’s not just strings that can be in JSON, it can be arrays, functions – basically any JavaScript, so it’s very useful. In fact, companies such as Google and Yahoo! are now using JSON and offer JSON outputs for their APIs. If it’s good enough for Google, it’s good enough for us!

Obviously, you’ll need some information to go on the map so let’s make a JSON file with some data in it. I’m going to make a map showing the weekend’s football fixtures and, to add some interest for the visitor, I’m going to put in some lovely football-related details about the matches. So let’s now make a JSON file called points.json:

{“markers”: [
{
“point”:new GLatLng(53.478093,-2.116116),
“homeTeam”: “Manchester United”,
“awayTeam”: “Arsenal”,
“information”: “Fusce adipiscing. Pellentesque semper risus eget eros.”,
“fixture”: “Sunday 4pm”,
“capacity”: “67,000”,
“previousScore”: “2-1”
},
{
“point”: new GLatLng(51.534229,-0.111312),
“homeTeam”: “Newcastle”,
“awayTeam”: “Chelsea”,
“information”: “Morbi at sapien. Quisque vitae eros nec orci elementum
bibendum.”,
“fixture”: “Saturday 3pm”,
“capacity”: “45,000”,
“tv”: “Eye TV”
}
] }

The next task is to put some markers on the map, based on the point value of each marker in the array named markers, and maybe have an information window containing some of the details. To make this possible, you’ll need to add some functions to map.js:

function createMarker(input) {
var marker = new GMarker(input.point);
GEvent.addListener(marker, “click”, function() {
marker.openInfoWindowHtml( input.homeTeam + “ vs. “ + input.awayTeam );
});
return marker;
}
function parseJson (doc) {
var jsonData = eval(“(“ + doc + “)”);
for (var i = 0; i < jsonData.markers.length; i++) {
var marker = createMarker(jsonData.markers[i]);
gmap.addOverlay(marker);
}
}
GDownloadUrl(“points.json”, function(data, responseCode) {
parseJson(data);
});

I’ll explain what’s going on with this segment of code from the bottom up. GDownloadUrl is part of Google Maps’ API and it uses AJAX to get the contents of the points.json file and passes the results to the parseJson function. The parseJson function takes the results and converts them from one long string of data into a nest of objects using the eval function. Now it’s possible to traverse the JSON file easily. You can then cycle through the array in the JSON file, sending each separate object to the createMarker function. The createMarker function places a marker on the map based on the point value and opens an information window when clicked, which will contain the home team name versus the away team name. After the function returns, the marker is added to the map using the API function addOverlay. See Fig 2 on the previous page for an example of how this all looks in action.

Fig 1


Fig 2


Fig 3


Fig 4


Fig 5


Formatting your bubbles

As you can see, the Google Maps’ API does a lot of the hard work for you, making it easy to work with. The only problem is that the bubbles look a bit boring at the moment. You can make them a bit more interesting by adding another function to the map.js file for formatting the text in the bubble:

function formatWindow (input) {
var html = “<div class=\”bubble\”>”;
html += “<h1>” + input.homeTeam + “ vs. “ + input.awayTeam + “</h1>”;
html += “<p>” + input.information + “</p>”;
html += “<p>”
if(input.fixture != null) {
html += “<strong>Kick-off:</strong> “ + input.fixture + “<br />”;
}
/* Some more formatting */
html += “</p></div>”;
return html;
}

This function takes in an object made from the JSON file and returns a string to go in the bubble. All that remains now is to call the function, so you’ll need to change the line in the createMarker function from:

marker.openInfoWindowHtml( input.homeTeam + “ vs. “ + input.awayTeam );

to:

marker.openInfoWindowHtml( formatWindow(input) );

This will call the function to receive the string of HTML to display in the bubble, showing the text that you want your visitors to see. See Fig 3 for an example.

If you’re wondering why your own bubble might not look exactly like the image, it’s because I’ve added some CSS styling to my HTML document. Bubbles in Google Maps can be formatted in the same way as any HTML. If you look at my formatWindow function, you can see that I’ve wrapped the HTML in the bubble in a div tag with the class name ‘bubble’. This means that in my CSS, I can add rules to format the contents of the bubble:

.bubble {
width: 350px;
}
.bubble h1 {
margin: 0;
padding: 0;
font-size: 150%;
}

Tabbed bubbles

The more information there is the more bubbles you’ll need, as well as a way of displaying large amounts of information in a small space. Luckily, the second version of Google Maps’ API offers tabbed windows, and they’re fairly easy to code. You just need to alter the createMarker function to accept an array of tabs:

function createMarker(input) {
var marker = new GMarker(input.point);
var tabs_array = [ new GInfoWindowTab(“Tab1”, “Tab 1 Information”),
new GInfoWindowTab(“Tab2”, “Tab 2 Information”) ];
GEvent.addListener(marker, “click”, function() {
marker.openInfoWindowTabsHtml(tabs_array);
});
return marker;
}

This function creates a new marker point and a new array of GInfoWindowTab objects, which takes two parameters – the tab title and the tab content. This array then gets passed to ‘openInfoWindowTabsHtml’ method, which creates a bubble with tabs that appears when the marker is clicked. See Fig 4.

Obviously tabs with ‘Tab 2 Information’ aren’t very exciting, so try to format the it. You can also add two (or more, it’s up to you) functions called formatTabOne and formatTabTwo – similar to the formatWindow function – to format each separate tab.

Changing your icons

It now looks great but there’s still more to do. The default markers aren’t the most attractive so make your own to replace them. PNGs usually give the best results for Google Maps and I recommend that your marker should be saved as one. You can add another function to the map.js file called makeIcon:

function makeIcon (image) {
var icon = new GIcon();
icon.image = image;
icon.shadow = “images/shadow.png”;
icon.iconSize = new GSize(16, 16);
icon.shadowSize = new GSize(24, 16);
icon.iconAnchor = new GPoint(8, 16);
icon.infoShadowAnchor = new GPoint(0, 0);
icon.infoWindowAnchor = new GPoint(8, 1);
return icon;
}

This function makes a new variable called ‘icon’, which is a GIcon, part of the Google Maps API. You can then specify what the icon will look like. Next, take the foreground icon image to be the argument of the function and set its foreground size (line four) and its shadow size (line five), and add anchors to the icon, which are all positioned from the top left of the foreground icon. iconAnchor (line six) is where the base of the foreground will sit on the map, infoShadowAnchor (line seven) is where the shadow’s top left corner sits in relation to the foreground, and infoWindowAnchor (line eight) anchors the bubble to the foreground image. The function then returns the object.

Let’s add some lines to the JSON file to let each marker know which image it wants the foreground icon image to be:

“markerImage”: “images/red.png”

This is just a path to where the image is in relation to the HTML file. Now you have to call the function somewhere, so let’s alter the line in the earlier createMarker function from:

var marker = new GMarker(input.point);

to:

var marker = new GMarker(input.point, makeIcon(input.markerImage) );

You should now get a map with some custom markers on it. As it’s a football map, what better to use than some football shirts?

To finish it off add some more matches to the JSON file, as there’s usually more than two matches played over the weekend. Now you should have a complete map. See Fig 5.

Google provides good documentation on its site (www.google.com/apis/maps/documentation/ – make sure you include the forward slash at the end when you etner the URL), which is helpful if you want to take the map even further. Check out some of the many services already based on Google Maps’ API to gain more inspiration. Luckily, Google takes all the hard work out of using its maps within your projects – its powerful API provides all the hooks you need for simple coding and quick results.


About the author:
Name:
Rik Lomas
Site: www.welovelocal.com
Areas of expertise: HTML, CSS, Javascript and PHP

 

Comments

Sue Perry / 15/10/2006 / 16:34

Are you sure this code works!? I have been trying for hours and though I can get the map to display fine, it doesn't show any markers.

I've copied your code pretty much from the mag / here and included my API key.

Colin / 17/10/2006 / 04:42 / http://www.vfs.com

Been at this for an hour, finally got it working.

It doesn't work for a number of reasons.

First off, if you're copying and pasting the code, be sure to do a find and replace on all quotes " ", as the format they are in does not copy properly. Do this in the HTML, Javascript and the JSON file.

Secondly, place all the extra functions within the onLoad function. If you place the other functions such as parseJson and createMarker outside of onLoad, nothing will work.

Make sure that this line
GDownloadUrl("points.json", function(data, responseCode) { parseJson(data);});

immediately follws this line
gmap.setCenter( new GLatLng(54.7,-4), 5);

and place all the functions below that. One of the main reasons that it doesn't work is that in the parseJson function it tries to reference gmap.

gmap.addOverlay(marker);

As gmap was defined outside the scope of this function it does not know what it is.

Also, in the JSON file, on the second marker
"information": "Morbi at sapien......

Make sure the whole thing is on one line...

Hopefully after that it should be up and running and ready for tweaking.

Best of luck.

Steve / 17/10/2006 / 14:52

I can't get this working either. Tried to follow Colin's comment but still no good.
Not a good tutorial when it doesn't work or is not easy to follow.

Tim / 18/10/2006 / 21:55

My advice - just go and check out the google api documentation. nice and clear.
http://www.google.com/apis/maps/

Gian Carlo / 20/10/2006 / 12:15 / http://www.gcmingati.net

I implemented the map with its basic functionalities (no bubbles) just adding this few lines AFTER the SRC of your PERSONAL API.
<script type="text/javascript">

//<![CDATA[

function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(41.895466, 12.482323), 10); // this is Rome, italy
map.addControl(new GLargeMapControl()); //draggable zoom
map.addControl(new GMapTypeControl()); //the basic 3 buttons maps, sat, hybris
}
}

//]]>
</script>
et voilà, just add a div with id "map".

Brian / 04/11/2006 / 06:00

Looks interesting. Can you put up a whole sample so that I and anyone else who reads this don't have to go through the pain others have in evaluating this approach?

Brian / 05/11/2006 / 09:55 / http://build-and-deliver.blogspot.com/

Interesting idea using the JSON instead of XML.

For all those who have had trouble in setting up the example, like me, I have created a basic example using this code. You can download it from here:
http://build-and-deliver.blogspot.com/2006/11/google-maps_05.html

I may add a few more of the features in as time allows.

Trish / 18/12/2006 / 13:56 / http://haligolightly.ca

Great article.

http://haligolightly.ca/testmap-json3.html

The above links to a map I adapted from the recipe on this site. It features as described above, 1) the custom info window formatting function (!) and 2) unique markers as referenced in the json file. I also added a clickable side panel/sidebar (how-to demonstrated in the alterations made between the files testmap-json2.html to testmap-json3.html)

Thanks for helping me make the move from xml to json. I found the former to be an extreme pain in the ass..

And hey, the .json file called on those maps call still contains leftovers from the sports match examples. Haha.


cheers!

fatima / 18/03/2007 / 13:12 / http://don't have

can i write the mobile number of person and then the computer find me where that peson is

Tee / 24/03/2007 / 17:51 / http://www.teebohne.de

Great article.
Many greetings from Germany

Tee

Jaysen Goreeba / 20/04/2007 / 13:46

Hi ya people. I wanted to know if you could help me by explaining to me is it possible for me open an infoWindowHtml bubble on a google map by clicking a hyperlink somewhere else but on the same web page, of course??

If you know please can you tell how can you achieve this because I don't really have a clue where to start. Unfortunately I am new to doing programming and any advice would be appreciated.

Thanks

Jaysen

Liam Giles / 23/04/2007 / 20:57 / http://www.spindogs.co.uk

Nice article thanks guys.

Can get some good info on interfacing with google maps direct from google to.

Adam / 19/05/2007 / 20:03 / http:www.cubixstudios.net

This is a really interesting article and something to take into account in the future. Google maps are great, has anyone got an opinion on microsofts new version... live maps?

Alex / 10/07/2007 / 12:22 / http://www.datravelers.com

Adam, for me personally, Google Maps are more convenient.

Andrew / 28/07/2007 / 14:08

This is a really badly written tutorial! I can only hope its better in the magazine! unfortunately I don't have the issue this one is in.

There should be final examples of the code, and perhaps a nice zip file with everything in it!

I hope the magazine reads these comments.

When it works, its great!

James / 29/08/2007 / 20:17 / http:www.cubixstudios.com

I dont really have that much to do with google maps as it hard to intergrate but this is a good article and if i get asked, i think ill give it a go

Jens / 20/09/2007 / 12:30 / http://www.lesestuff.de

Hi,

I need the tabs on the left or on the right. Is this possible too?

Duncan / 19/10/2007 / 09:52 / http://www.netring.co.uk

I must admit google maps is actually quite good fun to use, so if you can add it to your website thats even better.

:)

Sven / 23/10/2007 / 14:22 / http://vollfunny.de

<blockquote>Hi,

I need the tabs on the left or on the right. Is this possible too?</blockquote>

Yep, I worked out how to do that

jameel / 26/10/2007 / 08:33

I want a simple help i want to move a map in different direction that means up down right and left
when ever i click a buttin this button is an html button
so pls can u help me for this its urgent for me
i tried with map.movemap(0,100) so on
or map.MovePan(0.100) it giving object does not support property or method
thank u

Schmoo / 02/11/2007 / 01:42

Great article, and it's perfectly well-written in the context that it appears to me to be written - it's a demonstration rather than a cookie-cut solution, to teach methods rather than dish out code. Example code would be nice, sure, but I don't think that that's as important as some people are making out. And the quotes, I have no doubt, are the result of the some or other site-wide formatting gubbins. You're all presumably web developers, you should understand this :)

Mel / 05/11/2007 / 17:11 / http://starcraft2-blog.de

I've been trying to figure out how tabbed bubbles work for like forever.. thanks for the article, very well written :)

neeraj / 05/01/2008 / 09:12

the code is not explained in the sequence and step wise manner?

Anschi / 30/01/2008 / 13:35 / http://www.archicentral.com

Hi,
I'm just trying to get started with google map - and got the following problem. I have database with addresses and geodata - but it seems that the geodata is not very accurate - my marker never points on the exact address. So is it possible to set a marker just with the address data? Something like this:

map.addOverlay(new GMarker('105 Ingham Hill Road, Old Saybrook, CT'))

Thanks

Jeffrey Monroe / 27/03/2008 / 00:13 / http://www.interstartv.com

Has anyone used the personalized map creator to make their maps yet? It's seems really basic. You definetly don't have nearly as much control as you would if you followed the steps in this tutorial. I wonder if there is a way to export the basic things you did in the map creator and then edit it that AJAX by hand.

Harry Selent / 30/03/2008 / 13:13 / http://www.medicalcharting.com

Jeffrey, I have not gotten the perosnalized map creator to work yet, still working on it but it looks promising..

Gerardo / 05/04/2008 / 05:20 / http://www.volkdefense.com

Wow i didnt know AJAX was this hard...Tried it too but cant seem to get it working, any ideas?

Kairi / 23/06/2008 / 21:42

Hello,

I've tried the code and it wouldn't work. I've also tried following Colin's advice, but it failed to work too. Only showing the map, but it's missing the markers. What could be wrong?

Here's the link for the map test page I've made: http://www.subture.com/khairi/testarea/new.html

Really appreciate any help. Thanx in advance.

fcbfan / 02/07/2008 / 18:01

kairi, i've just got it working following colin comment.

what i did:
1)replace those wrong " in html, js, json
2)repair split lines
3)put GDownloadUrl method just after gmap.setCenter
4)add gmap parameter to GDownloadUrl so it looks like this:
GDownloadUrl("points.json", function(data, responseCode) {parseJson(data, gmap);});
5)add gmap to parseJson so it starts like this:
function parseJson (doc, gmap) {
4+5 repairs different scope of gmap

its what colin already said just in different words

CD / 10/07/2008 / 09:13

Hi,
how i will get automatic (from maps.google) the name of street at info-bubble ?

thanx in advance..

NetDominus / 03/08/2008 / 09:55 / http://www.netdominus.co.uk

I have uploaded a zip file of the files required to make this tutorial work as expected. You can get the final version at: http://www.netdominus.co.uk/downloads/google-map-with-json.zip

Peter Oravec / 03/09/2008 / 18:19 / http://www.peteroravec.sk

maps api is amazing but little hard to understand for me

Kevin / 17/09/2008 / 22:13 / http://www.whiterocksolutions.com/

There are some great step by step Google Map Tutorials on http://www.whiterocksolutions.com/ . They cover Google My Maps and the Google Maps API in easy to follow steps.

Kevin
White Rock Solutions

Adeel / 24/12/2008 / 18:17 / http://efirmSolutions.com

I tried this and it is working fine on my local machine but when I upload it on my hosting server, I get Syntax error for this line of code:

var jsonData = eval('(' + doc + ')')

Any idea how to resolve this issue?

Serkan / 31/01/2009 / 16:17 / http://www.bksbilgisayar.com

I tried this and it is working fine on my local machine but when I upload it on my hosting server, I get Syntax error for this line of code:

var jsonData = eval('(' + doc + ')')

Any idea how to resolve this issue?

Yes I need this code.. what is var jsonData = eval('(' + doc + ')')

Ronald McMeekin / 22/04/2009 / 16:24

Do you have some information on how to use google maps in Flash CS3 as I would like to use this feature of google but haven't had any success finding any tutorials or demo's to deconstruct and learn from please help.

John / 10/11/2009 / 10:20 / http://www.studentlettingspoint.com

Still havening problems getting this working :(

Add a comment

Your name:


Your email: (Not displayed)


Your website: (optional)


Enter your comment here:

.net magLatest issue Buy it

Issue 199

The web pro’s guide to Wordpress and 60 apps for improving your site Find out more ...

» Fantastic subscription offers
» Buy issue 199
» Get a corporate subs
» Join us on Facebook

 
Signup for our newsletter

Enter your email address and start receiving our new-look weekly email newsletter!

 
 

Pac

UK Web Hosting