Google Maps JavaScript API v2 (Deprecated)

Upgrading Your Google Maps JavaScript Application To v3

Version 2 of the Google Maps JavaScript API is no longer available. This guide is intended to help developers who are already using the Google Maps JavaScript API v2 migrate their code to version 3.

Miguel Angel Vilela, Google Enterprise Support Team
November, 2012

Quite a lot has changed between v2 and v3 of the Google Maps JavaScript API. As you start working with the new API, you will quickly find that this is not simply an incremental upgrade. The good news is that we've added a lot of great new features and improved the overall usability of the API from the developers standpoint. The bad news is that upgrading to v3 will require rewriting some of your code. If you're planning to upgrade from the Google Maps JavaScript API v2 to the Google Maps JavaScript API v3, this guide will help you through the process, and call out some of the most common changes for users of the v2 API.

  1. Overview
  2. Changes in v3
  3. Upgrading Your Application
  4. Summary
  5. Detailed Reference

Overview

Every application will have a slightly different migration process; however, there are some steps that are common to all projects:

  1. Get a new key. The Google Maps JavaScript API now uses Google's API Console to manage keys. Before you begin your migration, be sure get your new new API key.
  2. Update your API Bootstrap. Most applications will load the Google Maps JavaScript API v3 with the following code:
    <script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key=API_KEY&sensor=true_OR_false"></script>
    
  3. Update your code. The amount of change required will depend a lot on your application. Common changes include:
    • Always reference the google.maps namespace. In v3, all Google Maps JavaScript API code is stored in the google.maps.* namespace instead of the global namespace. Most objects have also been renamed as part of this process. For example, instead instead of GMap2, you will now load google.maps.Map.
    • Remove any references to obsolete methods. A number of general purpose utility methods have been removed, such as GDownloadURL and GLog. Either replace this functionality with third party utility libraries, or remove these references from your code.
    • (Optional) Add libraries to your code. Many features have been externalized into utility libraries so that each app will only have to load the parts of the API that will be used.
    • (Optional) Configure your project to use the v3 externs. The v3 externs can be used to help validate your code with the Closure Compiler, or to trigger autocomplete in your IDE. You can download the externs for current releases from: http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/maps/
  4. Test and iterate. At this point you will still have some work to do, but the good news is that you will be well on your way to your new v3 maps application!

Changes in Version 3 of the Google Maps JavaScript API

Before planning your migration, you should take time to understand the differences between the Google Maps JavaScript API v2 and the Google Maps JavaScript API v3. The newest version of the Google Maps JavaScript API has been written from the ground up, with a focus on modern JavaScript programming techniques, increased use of libraries, and a simplified API. Many new features have been added to the API, and several familiar features have been changed or even removed. This section highlights some of the key differences between the two releases.

Some of the changes in the v3 API include:

  • A streamlined core library. Many of the supplementary functions have been moved into libraries, helping to reduce the load and parsing times for the Core API which lets your map load quickly on any device.
  • Improved performance of several features, such as polygon rendering and marker placement.
  • A new approach to client-side usage limits to better accommodate shared addresses used by mobile proxies and corporate firewalls.
  • Support for the Model-View-Controller design pattern.
  • Added support for several modern browsers and mobile browsers. Support for Internet Explorer 6 has been removed.
  • Removed many of the general-purpose helper classes ( GLog or GDownloadUrl). Today, many excellent JavaScript libraries exist that provide similar functionality, such as Closure or jQuery.
  • An HTML5 Street View implementation that will load on any mobile device.
  • Custom Street View panoramas with your own photos, allowing you to share panoramas of ski slopes, houses for sale or other interesting places.
  • Styled Maps customizations that allows you to change the display of elements on the base map to match your unique visual style.
  • Support for several new services, such as the Weather Layer, ElevationService and Distance Matrix.
  • An improved directions services provides alternative routes, route optimization (approximate solutions to the Travelling Salesman Problem), bicycling directions (with bicycling layer), transit directions, and draggable directions.
  • An updated Geocoding format that provides more accurate type information than the accuracy value from the Geocoding API v2.
  • Support for multiple Info Windows on a single Map

Upgrading Your Application

Your New Key

There are two significant changes to keys in the Google Maps JavaScript API v3 release. First, a key is no longer required during early development. Second, the API uses a new key system. This means that your v2 key will not work with your v3 application. Adding a v3 key before deploying your application to production will:

The key is passed when loading the Google Maps JavaScript API v3. To generate a key:

  1. Visit the APIs Console at https://code.google.com/apis/console and log in with your Google Account.
  2. Click the Services link from the left-hand menu, and activate the Google Maps JavaScript API v3 service.
  3. Once the service has been activated, your API key is available from the API Access page, in the Simple API Access section. Maps API applications use the Key for browser apps.

Maps for Business Client IDs

If you are a Maps for Business customer, you will need to use a Client ID in place of a Key. Note that the two cannot be used together. Client IDs are similar to keys, but with the following differences:

  • Maps for Business applications using a Client ID may have access to additional features or limits, such as Maps Analytics.
  • Your Client ID will be given to you by Google Enterprise Support. You do not need to use the API Console.
  • When loading the Google Maps JavaScript API, you will use the client parameter instead of the key parameter. For example:
    <script src="//maps.googleapis.com/maps/api/js?v=3&client=gme-yourclientid&sensor=true_or_false" type="text/javascript"></script>
  • Client IDs are always prefixed with gme-.

Loading the API

The first modification that you'll need to make to your code involves how you load the API. In v2, you load the Google Maps JavaScript API through a request to http://maps.google.com/maps. If you are loading the Google Maps JavaScript API v3, you will need to make the following changes:

  1. Load the API from //maps.googleapis.com/maps/api/js
  2. Remove the file parameter.
  3. Make sure to include the required sensor parameter.
  4. Update the key parameter with your new v3 key. Maps for Business customers should use a client parameter.
  5. (Maps API for Business only) Ensure that the client parameter is supplied as explained in the Google Maps API for Business Developer's Guide.
  6. Remove the v parameter to request the latest released version or change its value accordingly to the v3 versioning scheme.
  7. (Optional) Replace the hl parameter with language and preserve its value.
  8. (Optional) Add a libraries parameter to load optional libraries.

In the simplest case, the v3 bootstrap will specify only your API key and sensor parameter:

<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key=API_KEY&sensor=false"></script>

The example below requests the latest (experimental) version of the JavaScript Maps API v2 in German:

<script type="text/javascript" src="//maps.google.com/maps?file=api&v=2.x&sensor=false&key=API_KEY&hl=de"></script>

The example below is an equivalent request for v3.

<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=API_KEY&language=de"></script>

Versioning

Loading a specific version is not required in v3. If you omit the version parameter, you will get the most recent experimental version of the API. If you prefer, you can specify a specific version number, the latest (experimental) version, or the most stable, frozen version. Before you launch your application, ensure that you are specifying either the current released or frozen version.

The table below maps the v2 version scheme to v3.

v2 v3 Use case
2.s 3.0 Frozen version. Oldest version available.
2 3 Release version. Latest stable version.
2.x 3.exp Experimental version. Never use the experimental version in production.

Important: The Maps API for Business SLA does not apply to the Experimental version. Maps API for Business applications must use the current Release or Frozen version to be covered by the SLA.

Introducing the google.maps namespace

Probably the most noticable change in the Google Maps v3 API is the introduction of the google.maps namespace. The v2 API places all objects in the Global namespace by default, which can result in naming collisions. Within v3, all objects are located within the google.maps namespace.

When migrating your application to v3 you will have to change your code to make use of the new namespace. Unfortunately, simply searching for "G" and replacing with "google.maps." won't completely work; but, it is a good rule of thumb to apply when reviewing your code. Below are some examples of the equivalent classes in v2 and v3.

v2 v3
GMap2 google.maps.Map
GLatLng google.maps.LatLng
GInfoWindow google.maps.InfoWindow
GMapOptions google.map.MapOptions
G_API_VERSION google.maps.version
GPolyStyleOptions google.maps.PolygonOptions
or google.maps.PolylineOptions

Removing Obsolete Code

The Google Maps JavaScript API v3 has parallels for most of the functionality in v2; however, there are some classes that are no longer supported. As part of your migration, you should either replace these classes with third party utility libraries, or remove these references from your code. Many excellent JavaScript libraries exist that provide similar functionality, such as Closure or jQuery.

The following classes have no parallel in the Google Maps JavaScript API v3:

GBoundsGLanguage
GBrowserIsCompatibleGLayer
GControlGLog
GControlAnchorGMercatorProjection
GControlImplGNavLabelControl
GControlPositionGObliqueMercator
GCopyrightGOverlay
GCopyrightCollectionGPhotoSpec
GDownloadUrlGPolyEditingOptions
GDraggableObjectGScreenOverlay
GDraggableObjectOptionsGStreetviewFeatures
GFactualGeocodeCacheGStreetviewLocation
GGeoAddressAccuracyGStreetviewOverlay
GGeocodeCacheGStreetviewUserPhotosOptions
GGoogleBarGTileLayerOptions
GGoogleBarAdsOptionsGTileLayerOverlayOptions
GGoogleBarLinkTargetGTrafficOverlayOptions
GGoogleBarListingTypesGUnload
GGoogleBarOptionsGXml
GGoogleBarResultListGXmlHttp
GInfoWindowTabGXslt
GKeyboardHandler

Comparing Code

Let's compare two, rather simple, applications that have been written with the v2 and the v3 APIs.

<!DOCTYPE html>
<html>
  <head>
    <script src="//maps.google.com/maps?file=api&v=2&key=API_KEY&sensor=false"
        type="text/javascript"></script>
    <style type="text/css">
      html, body, #map-canvas { height: 100%; margin: 0; }
    </style>
    <script type="text/javascript">
    function initialize() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(
            document.getElementById('map-canvas'));
        map.setCenter(new GLatLng(37.4419, -122.1419), 13);
        map.setUIToDefault();

        map.addOverlay(new GMarker(new GLatLng(37.4419, -122.1419)));

      }
    }
    </script>
  </head>
  <body onload="initialize()" onunload="GUnload()">
    <div id="map-canvas"></div>
  </body>
</html>
    
<!DOCTYPE html>
<html>
  <head>
    <script src="//maps.googleapis.com/maps/api/js?sensor=false"
        type="text/javascript"></script>
    <style type="text/css">
      html, body, #map-canvas { height: 100%; margin: 0; }
    </style>
    <script type="text/javascript">
    function initialize() {
      var map = new google.maps.Map(
        document.getElementById('map-canvas'), {
          center: new google.maps.LatLng(37.4419, -122.1419),
          zoom: 13,
          mapTypeId: google.maps.MapTypeId.ROADMAP
      });

      var marker = new google.maps.Marker({
            position: new google.maps.LatLng(37.4419, -122.1419),
            map: map
      });

    }
    google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>
    

As you can see, there are several differences between the two applications. Notable changes include:

  • The address from which the API is loaded has changed.
  • The GBrowserIsCompatible() and GUnload() methods are no longer required in v3, and have been removed from the API.
  • The GMap2 object is replaced by google.maps.Map as the central object in the API.
  • Properties are now loaded through Options classes. In the above example, we set the three properties required to load a map — center, zoom and mapTypeId — via an inlined MapOptions object.
  • The default UI is on by default in v3. You can disable this by setting the disableDefaultUI property to true in the MapOptions object.

Summary

At this point you'll have gotten a taste for some of the key points involved in your migration from the Google Maps JavaScript API v2 to the Google Maps JavaScript API v3. There is a lot more information that you may need to know, but it will depend upon your application. In the following sections, we have included migration instructions for specific cases that you may encounter. Additionally, there are several resources that you might find helpful during the upgrade process.

Should you have any issues or questions about this article, please use the Feedback on this Document link at the top of this page.

Detailed Reference

This section provides a detailed comparison of the most popular features of both version 2 and version 3 of the Google Maps JavaScript API. Each section of the reference is designed to be read individually. We recommend that you do not read this reference in its entirety; instead, use this material to aid your migration on a case-by-case basis.

  • Events - registering and handling events.
  • Controls - manipulating the navigational controls that appear on the map.
  • Overlays - adding and editing objects on the map.
  • Map Types - the tiles that make up the basemap.
  • Layers - adding and editing content as a group, such as KML or Traffic layers.
  • Services - working with Google's geocoding, directions or Street View services.

Events

The event model for the Google Maps JavaScript API v3 is similar to that used in v2, though much has changed under the hood.

Controls

The Google Maps JavaScript API displays UI controls that allow users to interact with your map. You can use the API to customize how these controls appear.

Overlays

Overlays reflect objects that you "add" to the map to designate points, lines, areas, or collections of objects.

Map Types

The types of maps available in v2 and v3 are slightly different, but all basic map types are available in both versions of the API. By default, v2 uses standard "painted" road map tiles. However, v3 requires a specific map type to be given when creating a google.maps.Map object.

Layers

Layers are objects on the map that consist of one or more overlays. They can be manipulated as a single unit and generally reflect collections of objects.

Services

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.