In usability we trust

UX and all things web

Google Maps API 3 – The basics

gmmlogoThe Google Maps API has evolved to version 3. This version is a complete rewrite and focuses primarily on speed. The new API also features new ways of using it. This article is the first in a series exploring version 3 of the Google Maps API. This first article will take a look on how to create a simple map and explain some differences from the previous version.

Background information

First of all, this is an early release of the new API and it’s still in Labs. It doesn’t contain all the features of the old API and will probably never do so since the old API is bloated with lots of helper methods for doing all sorts of things like making AJAX calls and showing log windows. Nowadays we have libraries like jQuery and Prototype and tools such as Firebug to take care of these things. Therefor these features will not be included in the new API, since it’s main focus is to be streamlined in order to be as fast as possible. Other missing features such as polygons and polylines will however probably eventually be included.

Secondly, since it’s an early release it’s still undergoing major changes. Features will be added as we go along and some changes of how to do certain things might be introduced.

That said, I think that the new API is mature enough to use and certainly to experiment with. It also contains the most common features seen in implementations on Google Maps on the Web.

Enough with the background info already! Let’s take a look of what the new API looks like.

Inserting a reference to the API

The first thing you will notice is that the API key is no longer necessary. In the previous versions the API key was inserted as a querystring into the script reference but not so anymore. This means that you don’t have to apply for a new API key for every domain you want to have a map at. It also means that the URI to the API is a lot shorter.

So the only thing you have to tell, while referencing the API, is whether your device has a sensor or not. sensor=false if you don’t have a sensor and sensor=true if you do. With a sensor is meant some way to determine your present location, like if you have a GPS in your device. This information is attached as querystring at the end of the URI.

<script type="text/javascript" src=""></script>

Creating a map

A new namespace

In previous versions of the API there were lots of global variables, distinguishing them selfs by having a capital G in the beginning, like GMap and GLatLng. In the new API the namespace google.maps is used. So what was formerly called GLatLng is now called google.maps.LatLng. Using namespaces is good coding praxis. One should avoid cluttering the global namespace as much as possible in order to avoid collisions with other code. Read more about why in Global variables in Javascript.

So in practical terms, here’s how to create a new coordinate object the old way and how to do it the new way. The LatLng() method takes two arguments, an x and an y coordinate.

// The old way
var latlng = new GLatLng(57.8, 14.0);
// The new way
var latlng = new google.maps.LatLng(57.8, 14.0);

Object literals

The new API makes heavy use of object literals to pass arguments to it’s methods. The old API used object literals as well, but in this version they’ve taken it a step further which I think is positive. I think this is a really beautiful way of coding. It’s easy to use, easy to maintain and easy to expand. For you who doesn’t know what an object literal is, it looks like this:

var myObj = {
  id: '1',
  name: 'Whatever'
alert(; // Will alert Whatever

It’s basically a fast and easy way to create a Javscript object. Some of you might also recognize it as JSON, and that’s exactly what it is. JSON stands for Javascript Object Notation and is in fact a Javascript Object.

Initializing the map

To initialize the map we need to call the constructor of the Map class. It takes two arguments the first one being a reference to a HTML elemtn where you want the map to be inserted (often <div id="map">) and the second one being an object literal (options) containing a set of properties.

This is much like how it works in the old API. The big difference is that in the old API you had to call the method setCenter() immediately after calling the constructor in order for the map to display. setCenter() told the map what location would be the center of the map and what the initial zoom level would be. In the new API this is not neccesary since both these properties are passed in the option parameter. So instead of making two calls, you now have to do only one. An approach that I think makes a lot more sense.

Before we get into the details of what properties option contains, lets have a look at what the code to create a map looks like.

// Creating a LatLng object containing the coordinate for the center of the map
var latlng = new google.maps.LatLng(57.8, 14.0);
// Creating an object literal containing the properties we want to pass to the map
var options = {
  zoom: 6,
  center: latlng,
  mapTypeId: google.maps.MapTypeId.ROADMAP
// Calling the constructor, thereby initializing the map
var map = new google.maps.Map(document.getElementById('map'), options);


The option parameter is, as mentioned before, an object literal containing the properties we want to pass to the map object. There are three required properties that must be passed to the map on initialization. These are:

  • center
    This property sets the center of the map and takes a coordinate of the type google.maps.LatLng
  • zoom
    This is a number that sets the initial zoom-level of the map
  • mapTypeId
    This property sets what kind of map type that would initially be used. The most common type is google.maps.MapTypeId.ROADMAP

There are of course lots of other properties that you can use when initializing the map, including which controls to display and which features to enable or disable. For a full list see the documentation.

Live example


A live demonstration of a simple map

I’ve put together a live example of how to add a Google Map v3 on a web page.


In conclusion I would say that the Google Maps API team has done several things right here. First of all by using a proper namespace, thereby not cluttering the global namespace. Secondly by heavy use of object literals to pass arguments. This way the API is more consistent and also easier to expand in future releases.

Please note that the API is still under development and is still undergoing changes. The way it works might change before the final release.

This is the first article in a series about the Google Maps API V3, so keep your eyes open for the next one which will explore the different properties for the map object and how you can use these to make the map behave and look differently.

My Google Maps book

If you found this article useful you might be interested in my book Beginning Google Maps API 3. It covers everything you need to know to create awesome maps on your web sites. Buy it on


  1. Hej och tak så mycket for the nice article. Have you found, in Google’s documentation, a list of features in ver 3 that are already included, to be included and those that shall be deprecated?

  2. To my knowledge such lists does not exist. You can however check out the documentation to see what features are implemented. I know that the API team continually updates it to reflect the API so you can trust that it is fairly complete.

  3. Tom, you can take a look at

    Gabriel, just one thing. I don’t need to pass center(at least) to the map initialization. This could be done using map.set_center (but yes, it’s necessary).

  4. Hi I am new to this google maps.. i liked ur article a lot… i was trying this .. bit i am just getting blank page…
    where am i going wrong?

    function initialize() {

    var latlng = new google.maps.LatLng(57.8, 14.0);
    var options = {

    zoom: 6,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP

    var map = new google.maps.Map(document.getElementById(‘map’), options);

  5. Hi Gouri,

    Try adding css rules for height and width to the div:


  6. Hi Everyone !
    i was trying to use the above code but always got a blank page.
    with a little modification it worked.
    in the body part use the code below ——-

    function initialize() {
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    var map = new google.maps.Map(document.getElementById(“map”), myOptions);

  7. Hi,
    I’m a beginner to google map api and also I have few knowledge about javascript.
    I have tried all the examples google provided, but there is no example that I can use my mouse to draw a line or polygon in a very convenient way. Of course, there is a way that I can click the start point and end point on the map, and then link the start point and end point, but that’s not what I want. Generally, we don’t draw line like that. Usually the place where the mouse is down is the start point of the line, and with the moving of the mouse, the end of line will change to the position of the mouse, when the mouse is up, the end point is set to the position where the mouse is up. In computer graphic, this is called XOR lines. I’d like to know how this could be realized in google map.

    Thanks a lot,

  8. Do we know if it’s possible to use v3 with localhost?

    I’ve been trying to test v3 but so far I’m not getting a map to display, and the only conclusion I can make is that it’s because I’m testing it on localhost.

  9. @Johan, I was confused same way. Like you I saved the demo file and opened it on localhost : but no map is visible.
    But it’s not a matter of host! It’s a matter of css file…
    Yes, if you happen to break the link to the css/style.css file, than the map is just not visible because you are missing the height definition included in the css file : #map { height:500px;}

  10. Hi,
    I have anything problem a display the map in the my page.
    I resolved with

    I use the attribute tag position:relative, and width-height a specific value width:480px; height:465px is not width:40%

    A other problem is the property option of the function Map()
    is visible:boolean, both you can use setVisible(visible:boolean) after call th function Map()

  11. Great post about getting started with Google Maps.

    Maybe the new map API from CloudMade is also worth a try, since it’s having some new and very useful features.

    My favorite is the possibility to customize the look of the map, so it can be optimized for routing, walking, sightseeing etc. You can see some examples here:

  12. wondering how to I override the google intelligence of serving static map to mobile devices and not the dynamic map 🙁

  13. Do you know if it’s possible to use geocode instead of latlng when initializing the script?
    So instead of
    var latlng = new google.maps.LatLng(57.8, 14.0);

    maybe you could have something like
    var latlng = new google.maps.geocode (1300 Main st, Town, State);

    or perhaps use the geocode info and covert it to latlng.

  14. Rheal Yes you can do that, but you need to perform the geocoding first and store the LatLng in a variable that you use later when initializing the map.

  15. RE: Rheal and Gabriel,

    If you were to perform the geocoding first, what would that look like? Below is a fictitious address. The script fetches some JSON data from google (my very first time ever dealing with JSON) and I’m completely clueless how to create the map to center around this.

    function initialize() {
    var myLatlng = new google.maps.LatLng(???);
    var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    var map = new google.maps.Map(document.getElementById(“map_canvas”),

    Am I going about this all wrong, or am I right on the edge of having this work? Any guidance would be most grateful!

  16. Ah, part of my comment got deleted. I’ll try again:

    html { height: 100% }
    body { height: 100%; margin: 0px; padding: 0px }
    #map_canvas { height: 100% }

    function initialize() {
    var myLatlng = new google.maps.LatLng(???);
    var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    var map = new google.maps.Map(document.getElementById(“map_canvas”),

  17. Ah, it’s cause I was posting javascript. So silly of me.

  18. Can you show an example that allows users to print their map including directions and/or markers using the API? I keep getting blank map with directions or maps with white blocks for markers. What am I doing incorrectly?

  19. I am trying to use a google map and have tried many different tutorials and google map documentation…I have had limited success.

    I can make a small map show on the webpage, but I cannot get a simple marker to work:
    Here is my javascript:

    function load() {

    if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(43.36, -116.12), 3);
    // Creating a marker and positioning it on the map
    var marker = new google.maps.Marker({
    position: new google.maps.LatLng(43.36, -116.12),
    map: map


    How come your online example does not have a API key anywhere?

  20. @kelsobrooks: Your problem is that you’re mixing Google Maps API v2 code with API v3 code. The new API (v3) doesn’t require an API-key.

  21. Thanks for the info!

    So…can anyone show me how to Show and simple map and how to add simple markers with basic labels?

    I still cannot get anything basic, everything is above what I am looking for…..

    Thanks again..


  22. I want to use google maps with markers. I want to get weather information for a particular latitude, longitude pair associated with the marker on click event. is there any short cut to do it or do i have to de-reference the whole thing and get the weather information i.e. use google reverse geo-coder to convert the latitude.longitude to a zip code and then get weather information for that zip code. i really wish there was a better way to do it, the above approach works independently with respect to the google api’s.

  23. From your book “Beginning Google Maps API3”, I have successfully done the exercise in chapter 5, listing 5-26.
    Now, instead of using hard coded latitude and longitude in a table, I modified listing 5-26, to read from a xml file that I have extracted from a mysql database.

    I am parsing the xml file with no trouble but I cannot get the markers to show on the map.
    Here is my code. Any idea ?

    // JavaScript Chapitre 5 Listing 5.10
    // map_ch05_10.js

    (function() {
    window.onload = function() {
    // Creating an object literal containing the properties
    // you want to pass to the map

    var options = {
    zoom: 3,
    center: new google.maps.LatLng(37.09, -95.71),
    mapTypeId: google.maps.MapTypeId.ROADMAP

    // Creating the map
    var map = new google.maps.Map(document.getElementById(‘map’), options);

    //getting the xml info
    downloadUrl(“phpsqlajax_generate_xml.php”, function(data) {
    //var xml = data.responseXML;
    var xml = parseXml(data);
    var markers = xml.documentElement.getElementsByTagName(“marker”);
    var i2=0

    for (var i = 0; i < markers.length; i++) {
    i2= i+1;
    alert ('i2' + i2);
    var type = markers[i].getAttribute("type");
    var point = new google.maps.LatLng(
    var marker = new google.maps.Marker({
    position: point,
    map: map,
    title: 'place nb '+i2,
    icon: '; + i2 + '.png'
    }); //fin marker
    } // end of for
    }); //end downloadUrl

    function downloadUrl(url, callback) {
    var request = window.ActiveXObject ?
    new ActiveXObject('Microsoft.XMLHTTP') :
    new XMLHttpRequest;

    request.onreadystatechange = function() {
    if (request.readyState == 4) {
    request.onreadystatechange = doNothing;
    callback(request, request.status);
    };'GET', url, true);

    function parseXml(str) {
    if (window.ActiveXObject) {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    return doc;
    else if (window.DOMParser) {
    return (new DOMParser).parseFromString(str, 'text/xml');

    // Wrapping the event listener inside an anonymous function
    // that we immediately invokie and passes the variable i to.
    (function(i, marker){
    // Adding an event-listener to the marker
    google.maps.event.addListener(marker, 'click', function(){
    var infowindow = new google.maps.InfoWindow({
    content: 'Place number' + i
    });, marker);
    })(i, marker);

    } // end 2nd function
    })(); //end 1st function

  24. I found my mistake, mentioned in my post, on March 28th.

    The following function, must be inside the for loop.

    // Wrapping the event listener inside an anonymous function
    // that we immediately invokie and passes the variable i to.
    (function(i, marker){
    // Adding an event-listener to the marker
    google.maps.event.addListener(marker, ‘click’, function(){
    var infowindow = new google.maps.InfoWindow({
    content: ‘Place number’ + i
    });, marker);
    })(i, marker);

  25. cool, that’s what I would like to implement using Google Map

  26. if display blank maps,
    change from


    thx to gio

  27. great source of info! i’ve just started transitioning into the v3 api, and this is what i need to get started! thanks!

  28. Lars Frederiksen, Denmark

    January 8, 2012 at 9:44 am

    Will your book include how to make javascripts that can solve this problem:
    – Put an address in the javascript
    – Geocode the address and place it in the map at the marker
    – Show the coordinates of the address on the HTML page

  29. i don’t know how to use it can you help me

  30. Excellent tutorial, far more concise and jargon free than google. It saved me a lot of time thanks 🙂

  31. I have added the required js and the api key and replaced the namespaces correctly but still I am not getting the map displayed on my website . Can anyone has a solution to this??

Leave a Reply

Your email address will not be published.