So your client emails you and asks, "Can you put one of those flashy maps on my contact page so that users can actually see our building from a satellite's view?". You've used Google maps many times, but there is only one problem: you have no idea how to use the API. Well get out your spoon and dig in!
* Click on the full-screen toggle.
Step 1: Obtain a Unique API Key
If you were to download the source code that is provided with this article, you would find that it doesn't work on your website. The reason is because Google requires all users to obtain a unique "API key" for each site that implements Google maps.
Never fear. It's 100% free and takes about thirty seconds to sign up. First, visit Google's sign up page and enter the url of your website. Don't worry about adding a specific path. The root url will cover every page that is part of that domain. Agree to the terms and conditions and click "Generate API".
That's it! The page that you've been redirected to contains your unique key as well as a sample page - to serve as a crash course. Your key will look something like:
ABQIAAAAAq93o5nn5Q3TYaaSmVsHhR1DJfR2IAi0TSZmrrsgSOYoGgsxBSG2a3MNFcUDaRPk6tAEpdWI5Odv
You'll also find a script path that will look like:
<script src="http://maps.google.com/maps?file=api&v=2ampkey=ABQIAAAAAq93o5nn5Q3TYaaSmVsHhR1DJfR2IAi0TSZmrrsgSOYoGgsxBSG2a3MNFcUDaRPk6tAEpdI5Odvw" type="text/javascript"></script>
Yours will be different from mine because it will contain your own specific key value. Copy this and paste it into the head portion of your document.
You might want to bookmark the link to the API documentation. You'll undoubtedly be referencing it as your skills progress.
Step 2: Setting Up Your HTML
For the sake of simplicity, we'll create a bare bones layout. Add the following within the body element of your document.
In a real world situation, you should move the styling to an external file (like I did in the video). The height and width values will by used by the API to determine the dimensions of your map. Don't worry, nothing will be clipped off.
Step 3: Javascript
Next, add the following to your Javascript file. Review it a bit and then continue on.
$(function() { // when the document is ready to be manipulated.
if (GBrowserIsCompatible()) { // if the browser is compatible with Google Map's
var map = document.getElementById("myMap"); // Get div element
var m = new GMap2(map); // new instance of the GMap2 class and pass in our div location.
m.setCenter(new GLatLng(36.158887, -86.782056), 13); // pass in latitude, longitude, and zoom level.
}
else {alert("Your browser is not worthy.");}
});
To take this code line by line:
- When the document is ready to be manipulated, run the code within.This is a jQuery syntax, but jQuery isn't required in the least. You could also simply add an "onLoad()" attribute to your body element - though this is messy.
- If the browser that the user is accessing the map from isn't compatible with the API, then show an alert (see bottom). Otherwise, run the code within.
- Create a variable called "map" and tell it to find the div that will contain the map.
- Next, create a variable called "m" and make it equal to a new instance of the "GMap2" class. Within the parenthesis, pass in the "map" variable that you just created previously
- Finally, set a center point so that the map knows what to show. To do this, we create a new instance of the "GLatLng" class and pass in the latitude and longitude values. You can go here to grab the appropriate values. In my case, I've set the coordinates to my home town. After that, you can optionally input a zoom level - which I've set to the standard '13'.
This code alone will give you a basic map that might be completely appropriate for your needs. However, if you'd like to also implement "zoom" and "map mode" features, read on.
Step 4: Refining Our Map
There are literally dozens of features that you can add to your map. We'll go over a few of them. First, we'll implement a zoom bar that will allows the users to incrementally zoom in or out.
m.addControl(new GLargeMapControl())
Here, we're taking our map and are adding a new control called "GLargeMapControl".
Next, let's add a feature that will allow the users to choose which map mode they desire - Normal, Satellite View, or a hybrid.
var c = new GMapTypeControl(); // switch map modes m.addControl(c);
- Create a variable called "c" and make it equal to a new instance of the "GMapTypeControl" class.
- Add a new control, and pass in "c".
If you refresh your browser, you'll see that the user nows has the option to choose his viewing mode. But what if you want to set the default mode? In such instances, you would use "setMapType".
m.setMapType(G_SATELLITE_MAP);
When defining the default mode, you have three choices.
- G_SATELLITE_MAP
- G_NORMAL_MAP
- G_HYBRID_MAP
You're Finished!
That wasn't too hard, was it? There are a few specific class names that you'll need to memorize, or jot down for later reference. But other than that, it's strikingly simple to implement such an advanced map into your websites.
For you template designers, why not implement this into one of the themes that you sell on ThemeForest?
A few days ago, we posted a tutorial that shows you how to combine many APIs - including Google maps. But many of you didn't know enough to get started. Hopefully, this will help. After you've wrapped your head around this API, why not save yourself some headaches and enlist the help of a PHP class called Phoogle? I think it's best to learn the right way first, but now that you have...cut some corners! See you next week.
Additional Resource
-

How to Create a Mashup By Combining 3 Different APIs
This tutorial will show you how to create a mashup of three different APIs including integration with Google Maps.
- Subscribe to the RSS Feed and the Video Feed for more daily web development tuts and articles.
Related Posts
Check out some more great tutorials and articles that you might like












User Comments
( ADD YOURS )matt October 15th
nice simple tutorial. Cheers.
Thomas Byttebier October 15th
If you don’t want to do the codework yourself, you may want to take a look at GMapEz: http://n01se.net/gmapez/
Great post anyway! Thanks.
Patrick October 15th
nice, clean and as short as possible. good work, thank you
Chris October 15th
Why, for any reason, would you load JQuery into this? It’s a huge file, just to accomplish something you can do with onLoad??
Jeffrey Way October 15th
@Chris - First, I said in the video that it wasn’t really required. But for just about all of my projects, I use jQuery in some way or another - so it’s an obvious choice.
Keep in mind that, although this is a barebones examples, a real world website will not be. In such cases, using the library makes perfect sense.
Lastly, the jQuery library is about 15kb packed. I’d hardly call that “huge”.
Lamin Barrow October 15th
This is the second post about consuming mashup APIs.I love this kind of stuff. Plz keep em coming.
Roshan October 15th
Yep simple and easy. Thanks man.
Roshan
http://www.instantshift.com
Chris October 15th
@Jeffrey: That’s quite large when I can write a fairly large HTML file that’s 15kb. An extra 15kb, first off, is probably about 100% as large as the page itself, for one function that’s already built into the browser’s JavaScript implementation.
Secondly, if you get around 10,000 hits a day, (fairly decent sized site), that’s an extra 150MB in bandwidth per day. For shared hosting plans, like what a lot of businesses run their pages on, that can add up pretty quick. 4.5GB of extra bandwidth per month.
Nothing against your tutorial, it’s great and all. I just recommend that in building a live site, keep the unnecessary stuff out and keep your clients (and their visitors!) happy
Aditya October 15th
Hmm, so jquery is a problem for big sites? I don’t mind paying up for the bandwidth, because it saves me many lines of code, and I don’t need to learn a new zany syntax just for the sake of the library, because I am comfortable with php syntax, and its pretty easy to jump to jquery!
Of course, when you are talking ‘clients’ though, my argument is doomed. Then I have to go back to crazy old DOM scripting again…
Jeffrey Way October 15th
Hey Chris,
I agree about the bandwidth remark. Good point.
But, when building a large site, many many developers will use a Javascript library. NETTUTS does.
–
But it doesn’t really matter. Whether or not to use jQuery is somewhat beside the point. People can adapt the tutorial to fit their own needs.
Great points.
Aditya October 15th
And oh yeah, I almost forgot, thanks for the gr8 tut!
Simon Vallee October 15th
Super useful post! On a side note, does anyone know which handwritten font is used to annotate this tutorial’s screenshots?
Jeffrey Way October 15th
@Simon - I’m glad you enjoyed it. The name of the handwritten font is “Marydale”.
Simon Vallee October 15th
@Jeffrey - Thanks! Much appreciated!
insic October 15th
Very helpful tutorial. Thank you.
pixelsoul October 15th
Thanks for this! I was racking my brain once with a customer that wanted this but I got lucky and they changed their mind about it.
Jbcarey October 16th
YES! I SOOOO needed this
Ian Yates October 16th
Useful tut and, of course, useful API! It might be even more useful if someone covers css styling with Google maps at some point - creative ways of displaying them. There’s a lot of head-banging amongst designers (myself included) trying to style Google’s route planner table for example..
Ben Griffiths October 16th
Excellent, thanks
Will M October 16th
Great stuff, cheers! Now any chance of getting a similar tut for adding custom icons and information to Google Maps?
Jash Sayani October 16th
Hi, Great Screencast and tutorial. Thanks a million !!
Could you please post about using the Google API with the Yahoo! FireEagle API and sending the location information to the Y! account…? Would be really helpful. Thanks.
tkenny October 16th
I’ve just completed implementing muiltMaps into a project and the process of setting up is very similar but its not free. I wonder why the client chose multiMaps rather than going for Google Maps which is free?
Oh well, this is a handy screencast that I’m sure I will return to when I have to implement Google Maps into a project. Thanks.
Kevin Quillen October 16th
jQuery is quite invaluable. I have used it with Google Maps in the past to create a mapping system for a real estate company so they can pinpoint listings on a map where Google fails to correctly pin them. Using the API and jQuery, I created a click event that used jQuery’s AJAX method to update the database for that listing instantly and it took far less coding than with regular Javascript. Just sayin.
At 15kb, jQuery is one of the smallest libs.
Custom icons would be a good tutorial and marker manager too.
Jeffrey Way October 16th
@tkenny - That is strange that they would choose MultiMaps over Google. Strange unless MM offers some extra features that I’m unaware of.
Rob October 16th
First off, great tutorial — I’ve been meaning to look into the Google Maps API for a project idea and this will be very helpful.
Now, it should be noted that the Google Maps API is not needed for those who want just a map of their business on their site.
You can enter your address on the Google Maps site and then click the ‘Link’ link found in the top-right corner just above the map. This will give you the embed code for dropping it into your site. You can click the ‘Customize and preview embedded map’ link if you need to modify the size etc. of the map.
For extra credit, you can register your business with the Local Business Center provided by Google Maps. This allows your business information (i.e. address, phone, url, description, etc.) to be displayed on the map of your business that you embed onto your site.
Dan October 16th
Short Sweet to the Point. Thanks
Antanas October 18th
to Chris: well, using javascript library saves a lot of time, so in some way i can say it saves money (client’s money). So maybe traffic problem isn’t so big as it seems
and we shouldn’t forget that all browsers supports cacheing, so amounts of gigabytes would be smaller.
Shane October 18th
Good screencast - its amazing that the Google Maps API affords developers so much for so little effort.
Shellee October 19th
Hey guys… if any of you knows how to use this thing please let me know. I recently got a script that uses google maps. I have the API but it really is no good as it shows random addresses and I need it to focus on one country only….
anhavana at yahoo dot co.uk
Sean O October 20th
The argument about loading in jQuery is silly. 15k is about as small as you can get for any library. And any concerns about bandwidth are negated if you simply load the library from Google’s hosted code repository:
http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js
Downloading from Google leads to $0 in bandwidth costs, and as more developers point to the same resource, chances are that many clients will have this cached anyway.
Jord October 20th
I wonder if theres a way of doing this dynamically, without entering the Longitude and Latitude manually? I’m currently building a site that requires a google map to show the location of offices, but there are 50+ office pages on the site.
Designer October 21st
this is very useful. u have solved one major problem for most of us.
Sean Halliday October 21st
I’ve create a website using Google Maps and would love to hear some feedback on layout, color scheme, ease of navigation etc….
The site is: http://www.thetricitiesbest.com
Thank you in advance for your time,
Sean B. Halliday
ben October 27th
Love the post! How do you display multiple places (with textNodes) in the same map?
Sean Halliday October 28th
I used an xml file to hold the data and it reads the information inputed in the xml file.
Andy Gongea November 3rd
Hey Jeffrey,
Can you add custom maps on top of the Google ones?
For example, I want to add my own layer, an additional one with different style - can Google Maps support that?
Arjen November 5th
Very useful, I’m going to use this for sure. Thanks!
Brandon November 26th
Website owners could also consider using MapMyPage.
http://www.mapmypage.com
Just copy one line of JavaScript into a web page and MapMyPage will automatically add Google Maps to the locations mentioned in the page.
For example, MapMyPage will identify the address on a contact page and add a Google Map.
MapMyPage includes features such as Panaramio photos and Wikipedia articles as well as integration with the Google Earth Plugin.
It doesn’t require the website owner to get a Google Maps API key.
Give it a try!
Add Your Comment
( GET A GRAVATAR )Your Name January 9th
Trackbacks