How to use the Google Maps API

This is How You Use the Google Maps API – screencast

Oct 15th in Screencasts by Jeffrey Way

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!

PG

Author: Jeffrey Way

Hi, I'm Jeff. I'm the editor of Nettuts+, and the Site Manager of Theme Forest. I spend too much time in front of the computer and find myself telling my fiance', "We'll go in 5 minutes!" far too often. I just can't go out to dinner while I'm still producing FireBug errors...drives me crazy. During my free time, I sporadically write articles for my own personal blog. If it will keep you in the good graces of the church, follow us on Twitter.

* 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".

Generate Key

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.

Sign Up Complete

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.

Layout
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

  • Create A Mashup By Combine 3 APIs

    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.

    Visit Article

    • 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

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    matt October 15th

    nice simple tutorial. Cheers.

    ( Reply )
  2. PG

    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.

    ( Reply )
  3. PG

    Patrick October 15th

    nice, clean and as short as possible. good work, thank you :)

    ( Reply )
  4. PG

    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??

    ( Reply )
  5. PG

    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”.

    ( Reply )
  6. PG

    Lamin Barrow October 15th

    This is the second post about consuming mashup APIs.I love this kind of stuff. Plz keep em coming.

    ( Reply )
  7. PG

    Roshan October 15th

    Yep simple and easy. Thanks man.

    Roshan
    http://www.instantshift.com

    ( Reply )
  8. PG

    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 :)

    ( Reply )
  9. PG

    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…

    ( Reply )
  10. PG

    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. :)

    ( Reply )
  11. PG

    Aditya October 15th

    And oh yeah, I almost forgot, thanks for the gr8 tut!

    ( Reply )
  12. PG

    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?

    ( Reply )
  13. PG

    Jeffrey Way October 15th

    @Simon – I’m glad you enjoyed it. The name of the handwritten font is “Marydale”.

    ( Reply )
  14. PG

    Simon Vallee October 15th

    @Jeffrey – Thanks! Much appreciated!

    ( Reply )
  15. PG

    insic October 15th

    Very helpful tutorial. Thank you.

    ( Reply )
  16. PG

    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.

    ( Reply )
  17. PG

    Jbcarey October 16th

    YES! I SOOOO needed this

    ( Reply )
  18. PG

    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..

    ( Reply )
  19. PG

    Ben Griffiths October 16th

    Excellent, thanks :)

    ( Reply )
  20. PG

    Will M October 16th

    Great stuff, cheers! Now any chance of getting a similar tut for adding custom icons and information to Google Maps?

    ( Reply )
  21. PG

    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.

    ( Reply )
  22. PG

    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.

    ( Reply )
  23. PG

    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.

    ( Reply )
  24. PG

    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.

    ( Reply )
  25. PG

    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.

    ( Reply )
    1. PG

      Franklin Boozabelt April 13th

      Thanks Rob… That is exactly what I was thinking…

      ( Reply )
  26. PG

    Dan October 16th

    Short Sweet to the Point. Thanks

    ( Reply )
  27. PG

    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.

    ( Reply )
  28. PG

    Shane October 18th

    Good screencast – its amazing that the Google Maps API affords developers so much for so little effort.

    ( Reply )
  29. PG

    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

    ( Reply )
  30. PG

    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.

    ( Reply )
  31. PG

    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.

    ( Reply )
    1. PG

      Michael May 11th

      It is possible to do it dynamically but not recommended. Let me explain. You do have to have the latitude and longitude, that’s just how google maps works. To get the lat and long dynamically you will have to use their geocoder. There is a RESTful one over HTTP (if you want to do it on pageload) and a javascript one as well and they are fairly easy to use. (see http://code.google.com/apis/maps/documentation/geocoding/ ) Once your code runs the geocoder it gets the latitude and longitude in return and you can plug that into your map.

      Here’s the problem though – you are currently limited to 15,000 geocodes per 24hr period (http://code.google.com/support/bin/answer.py?answer=93464&topic=12266). If you have a big map with a lot of points and it gets loaded enough each day, it could possibly hit that. I did a quick estimate with my situation and decided it could eventually threaten that so now I am saving lat and long with my locations in the db and only geocode when new locations are added or they are edited.

      Good luck!

      ( Reply )
  32. PG

    Designer October 21st

    this is very useful. u have solved one major problem for most of us.

    ( Reply )
  33. PG

    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

    ( Reply )
  34. PG

    ben October 27th

    Love the post! How do you display multiple places (with textNodes) in the same map?

    ( Reply )
  35. PG

    Sean Halliday October 28th

    I used an xml file to hold the data and it reads the information inputed in the xml file.

    ( Reply )
  36. PG

    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?

    ( Reply )
  37. PG

    Arjen November 5th

    Very useful, I’m going to use this for sure. Thanks!

    ( Reply )
  38. PG

    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!

    ( Reply )
  39. PG

    Timo January 18th

    Hi Jeffrey, lovely tutorial, thanks a lot! As a Javascript newbie I found the API on the Google website quite overwhelming. Thanks to your tutorial I’ve finally managed to get it working.

    One last question: How can I include something like this…

    … on my page without using any messy inline statements (my CMS can’t cope with them). According to Google this will prevent memory leaks in IE.

    Thanks for any feedback.

    http://www.designbits.de

    ( Reply )
  40. PG

    JiangNan January 20th

    How to use the key words for location the map,but not the coordinate.

    ( Reply )
  41. PG

    Muhammad Shafiq February 2nd

    It s best.but i have a problem,i had assign coordinate of my city mardan NWFP pakistan which is 34.2,72.0333 bt it does not go to roads and streat view.how can i get it?

    ( Reply )
  42. PG

    ketan February 16th

    Great Tutorial.

    Can u please suggest some web site where I can get fancy marker to place it on GoogleMap.
    I want to show the Machine Status Indicator.

    Thanks.
    Ketan

    ( Reply )
  43. PG

    SHamsa March 13th

    from where you got the “jquery” file???

    ( Reply )
  44. PG

    Ronald May 17th

    This works ! ! ! very nice tutorial. You need the jquery, tried to remove it this does not work.

    One question, what tools did you use in your demo ? what elearning software is that ?

    Thanks

    ( Reply )
  45. PG

    martin indiatsi July 11th

    how do you set more that one specific point on the map that you could add information to such as links and pictures.

    ( Reply )
  46. PG

    Paul Grace July 24th

    Great tutorial!! Thanks…it was a big help

    ( Reply )
  47. PG

    Michael August 13th

    The link to the demo is dead : [

    ( Reply )
  48. PG

    Peter September 5th

    Ahhhh Finally I found this your post as a true and easy tutorial about Google map integration..

    Thanks n keep it up!!!

    ( Reply )
  49. PG

    Brian October 9th

    Hey, Jeffery – Excellent basic lesson on GMap API. How about a sequel which shows how to use your own custom map and the new version 3 API??

    I have a task which would be perfect for the Google API, however it envolves a [custom] campus map. I’ve heard this is possible, but not sure how to go about it.

    ( Reply )
  50. PG

    Ru October 30th

    Hi the screen cast was very helpful thanks, reading through Google i was getting overwhelmed with the API Reference Guide and couldn’t visualize how each class is used to come up with a simple map like yours!

    How i insert the little pointer that one can click on to view the bubble message?

    Or is this screen cast coming in the future?

    ( Reply )
  51. PG

    Angelos Kar October 31st

    Is it possible to embed two maps on the same page? I tried but I didn’t manage to accomplish it…

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    October 31st