Upgrading Your Maps JavaScript API Application from V2 to V3

The Maps JavaScript API v2 is no longer available as of May 26, 2021. As a result, your site's v2 maps will stop working, and will return JavaScript errors. To continue using maps on your site, migrate to the Maps JavaScript API v3. This guide will help you through the process.

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 Maps JavaScript API now uses the Google Cloud Console to manage keys. If you are still using a v2 key, be sure to get your new API key before you begin your migration.
  2. Update your API Bootstrap. Most applications will load the Maps JavaScript API v3 with the following code:
    <script src="//maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></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 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 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. Learn more about Advanced Compilation and Externs.
  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 V3 of the Maps JavaScript API

Before planning your migration, you should take time to understand the differences between the Maps JavaScript API v2 and the Maps JavaScript API v3. The newest version of the 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.
  • 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 ElevationService and Distance Matrix.
  • An improved directions services provides alternative routes, route optimization (approximate solutions to the traveling salesperson 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

The Maps JavaScript API v3 uses a new key system from v2. You may already be using a v3 key with your application, in which case no change is needed. To verify, check the the URL from which you load the Maps JavaScript API for its key parameter. If the key value starts with 'ABQIAA', you are using a v2 key. If you have a v2 key, you must upgrade to a v3 key as a part of the migration, which will:

The key is passed when loading the Maps JavaScript API v3. Learn more about generating API keys.

Note that if you are a Google Maps APIs for Work customer, you may be using a client ID with the client parameter instead of using the key parameter. Client IDs are still supported in Maps JavaScript API v3 and do not need to go through the key upgrade process.

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 Maps JavaScript API through a request to http://maps.google.com/maps. If you are loading the 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. Update the key parameter with your new v3 key. Google Maps APIs for Work customers should use a client parameter.
  4. (Google Maps Platform Premium Plan only) Ensure that the client parameter is supplied as explained in the Google Maps Platform Premium Plan Developer's Guide.
  5. Remove the v parameter to request the latest released version or change its value accordingly to the v3 versioning scheme.
  6. (Optional) Replace the hl parameter with language and preserve its value.
  7. (Optional) Add a libraries parameter to load optional libraries.

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

<script src="//maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

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

<script src="//maps.google.com/maps?file=api&v=2.x&key=YOUR_API_KEY&hl=de"></script>

The example below is an equivalent request for v3.

<script src="//maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&language=de"></script>

Introducing the google.maps namespace

Probably the most noticeable change in the Maps JavaScript API v3 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, 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 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 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=YOUR_API_KEY"></script>
    <style>
      html, body, #map { height: 100%; margin: 0; }
    </style>
    <script>
    function initialize() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(
            document.getElementById('map'));
        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"></div>
  </body>
</html>
    
<!DOCTYPE html>
<html>
  <head>
    <script src="//maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
    <style>
      html, body, #map { height: 100%; margin: 0; }
    </style>
    <script>
    function initialize() {
      var map = new google.maps.Map(
        document.getElementById('map'), {
          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"></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 v2 to v3 of the Maps JavaScript API. There is 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 SEND FEEDBACK link at the top of this page.

Detailed Reference

This section provides a detailed comparison of the most popular features for both v2 and v3 of the 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 Maps JavaScript API v3 is similar to that used in v2, though much has changed under the hood.

Controls

The 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