Upgrading Your Maps JavaScript API Application from V2 to V3Stay organized with collectionsSave and categorize content based on your preferences.
AI-generated Key Takeaways
Google Maps API v2 is retired and websites using it must migrate to v3.
Migration involves obtaining a new API key, updating the API loading code, and adapting application code to v3's namespace and objects.
V3 offers numerous improvements, including enhanced performance, modernized client-side usage limits, wider browser support, new features, and updated services.
Key code changes include using thegoogle.mapsnamespace, replacing obsolete methods, and adopting v3's approach to controls, overlays, and services.
Developers should consult the provided v3 documentation and resources for detailed guidance and code examples during migration.
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:
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 yournew API keybefore you begin your migration.
Update your API Bootstrap.Most applications will load
the Maps JavaScript API v3 with the following code:
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 thegoogle.maps.*namespace instead of the global
namespace. Most objects have also been renamed as part of this
process. For example, instead ofGMap2, you
will now loadgoogle.maps.Map.
Remove any references to obsolete methods.A number
of general purpose utility methods have been removed, such asGDownloadURLandGLog.
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 theClosure
Compiler, or to trigger autocomplete in your IDE.
Learn more aboutAdvanced Compilation and Externs.
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 intolibraries,
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 toclient-side
usage limitsto better accommodate shared addresses used by mobile
proxies and corporate firewalls.
Removed many of the general-purpose helper classes (GLogorGDownloadUrl). Today, many
excellent JavaScript libraries exist that provide similar functionality,
such asClosureorjQuery.
An HTML5 Street View implementation that will load on any mobile device.
Custom
Street Viewpanoramas with your own photos, allowing you to share
panoramas of ski slopes, houses for sale or other interesting places.
Styled Mapscustomizations let you change the display of
elements on the base map to match your unique visual style.
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 itskeyparameter. 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:
Note that if you are a Google Maps APIs for Work customer, you may be using a client ID
with theclientparameter instead of using thekeyparameter. Client IDs are still supported in
Maps JavaScript API v3 and don't need to go through the key upgrade process.
Load 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 tohttp://maps.google.com/maps. If you are
loading the Maps JavaScript API v3, you will need to make the following
changes:
Load the API from//maps.googleapis.com/maps/api/js
Remove thefileparameter.
Update thekeyparameter with your
new v3 key. Google Maps APIs for Work customers should use aclientparameter.
Probably the most noticeable change in the Maps JavaScript API v3 is the
introduction of thegoogle.mapsnamespace. 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 thegoogle.mapsnamespace.
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
Remove 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 asClosureorjQuery.
The following classes have no parallel in the Maps JavaScript API v3:
GBounds
GLanguage
GBrowserIsCompatible
GLayer
GControl
GLog
GControlAnchor
GMercatorProjection
GControlImpl
GNavLabelControl
GControlPosition
GObliqueMercator
GCopyright
GOverlay
GCopyrightCollection
GPhotoSpec
GDownloadUrl
GPolyEditingOptions
GDraggableObject
GScreenOverlay
GDraggableObjectOptions
GStreetviewFeatures
GFactualGeocodeCache
GStreetviewLocation
GGeoAddressAccuracy
GStreetviewOverlay
GGeocodeCache
GStreetviewUserPhotosOptions
GGoogleBar
GTileLayerOptions
GGoogleBarAdsOptions
GTileLayerOverlayOptions
GGoogleBarLinkTarget
GTrafficOverlayOptions
GGoogleBarListingTypes
GUnload
GGoogleBarOptions
GXml
GGoogleBarResultList
GXmlHttp
GInfoWindowTab
GXslt
GKeyboardHandler
Compare Code
Here's a comparison of two applications that have been written with
the v2 and the v3 APIs.
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.
TheGBrowserIsCompatible()andGUnload()methods are no longer required in v3, and have been removed from the
API.
TheGMap2object is replaced bygoogle.maps.Mapas 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,zoomandmapTypeId— using an inlinedMapOptionsobject.
The default UI is on by default in v3. You can disable this by
setting thedisableDefaultUIproperty to true in theMapOptionsobject.
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.
The Maps JavaScript API v3Developers Documentationis the best place to learn more about the API and how it works.
The Maps JavaScript API v3Referencewill help you learn more about the new classes and methods in the v3 API.
The Stack Overflow community is a great place to ask your code
related questions. On the site, questions and answers relating to the
Maps JavaScript API use the
'google-maps'
or 'google-maps-api-3'
tags.
Should you have any issues or questions about this document, use
theSEND FEEDBACKlink 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 don't read this reference in its entirety; instead, use this
material to aid your migration on a case-by-case basis.
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.
New Event for MVC Support
The v3 API adds a new type of event to reflect MVC state changes. There
are now two types of events:
User events (such as "click" mouse events) are propagated from
the DOM to the Maps JavaScript API. These events are separate and
distinct from standard DOM events.
MVC state change notifications reflect changes in Maps API objects
and are named using aproperty_changedconvention.
Each Maps API object exports a number of named events. Applications
interested in specific events should register event listeners
for those events and execute code when those events are received. This
event-driven mechanism is the same in both the Maps JavaScript API
v2 and v3, except that the namespace has changed
fromGEventtogoogle.maps.event:
GEvent.addListener(map,'click',function(){alert('You clicked the map.');});
google.maps.event.addListener(map,'click',function(){alert('You clicked the map.');});
Remove Event Listeners
For performance reasons, it's best to remove an event listener when it is
no longer needed. Removing an event listener works the same way in v2 and
v3:
When you want to remove the event listener, pass this object to theremoveListener()method (GEvent.removeListener()in v2 orgoogle.maps.event.removeListener()in v3) to remove
the event listener.
Listen to DOM Events
If you want to capture and respond to DOM (Document Object Model)
events, v3 provides thegoogle.maps.event.addDomListener()static method, equivalent to theGEvent.addDomListener()method in v2.
Use Passed Arguments in Events
UI events often pass an event argument which can then be accessed by
the event listener. Most event arguments in v3 have been simplified
to be more consistent over objects in the API. (Consult thev3 Referencefor details.)
Nooverlayargument exists in v3 event listeners. If you
register aclickevent on a v3 map the callback will only
occur when the user clicks on the base map. You can register additional
callbacks on clickable overlays if you need to react to those clicks.
// Passes an overlay argument when clicking on a mapvarmap=newGMap2(document.getElementById('map'));map.setCenter(newGLatLng(-25.363882,131.044922),4);map.setUIToDefault();GEvent.addListener(map,'click',function(overlay,latlng){if(latlng){varmarker=newGMarker(latlng);map.addOverlay(marker);}});
// Passes only an event argumentvarmyOptions={center:newgoogle.maps.LatLng(-25.363882,131.044922),zoom:4,mapTypeId:google.maps.MapTypeId.ROADMAP};varmap=newgoogle.maps.Map(document.getElementById('map'),myOptions);google.maps.event.addListener(map,'click',function(event){varmarker=newgoogle.maps.Marker({position:event.latLng,map:map});});
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.
Changes in Control Types
Some changes tocontroltypes have been introduced
with the v3 API.
The v3 API supports additionalmap typesincluding terrain maps and the ability to add custom map types.
The v2 hierarchical control,GHierarchicalMapTypeControl, is no longer available.
You can achieve a similar effect by using thegoogle.maps.MapTypeControlStyle.HORIZONTAL_BARcontrol.
The horizontal layout provided byGMapTypeControlin v2 is not available in v3.
Add Controls to the Map
With the Maps JavaScript API v2 you would add controls to
your map through theaddControl()method of your map
object. In v3, instead of accessing or modifying controls directly,
you modify the associatedMapOptionsobject. The
below sample shows how to customize the map to add the following
controls:
buttons that let the user toggle between available map types
Positioning controls has changed a great deal in v3. In v2, theaddControl()method takes an optional second parameter
that lets you specify the position of the control relative to the
corners of the map.
In v3, you set the position of a control through thepositionproperty of the control options. Positioning of
these controls is not absolute; instead, the API lays out
the controls intelligently by "flowing" them around existing map
elements within given constraints (such as the map size).
This layout makes sure that default controls are compatible with your controls.
SeeControl
Positioning in v3for more information.
The following code re-positions controls from the above samples:
varmap=newGMap2(document.getElementById('map'));map.setCenter(newGLatLng(-25.363882,131.044922),4);// Add map type controlmap.addControl(newGMapTypeControl(),newGControlPosition(G_ANCHOR_TOP_LEFT,newGSize(10,10)));// Add scalemap.addControl(newGScaleControl(),newGControlPosition(G_ANCHOR_BOTTOM_RIGHT,newGSize(20,20)));
varmyOptions={center:newgoogle.maps.LatLng(-25.363882,131.044922),zoom:4,mapTypeId:google.maps.MapTypeId.ROADMAP,// Add map type controlmapTypeControl:true,mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.HORIZONTAL_BAR,position:google.maps.ControlPosition.TOP_LEFT},// Add scalescaleControl:true,scaleControlOptions:{position:google.maps.ControlPosition.BOTTOM_RIGHT}};varmap=newgoogle.maps.Map(document.getElementById('map'),myOptions);
Custom Controls
Use the Maps JavaScript API to create custom navigational controls.
To customize controls with the v2 API, you would subclass theGControlclass and define handlers for theinitialize()andgetDefaultPosition()methods.
There is no equivalent to theGControlclass in v3. Instead,
controls are represented as DOM elements. To add a custom control
with the v3 API, create a DOM structure for the control in a
constructor as a child of aNode(e.g. a<div>element) and add event listeners to handle any
DOM events. Push theNodeinto the maps'controls[position]array to add an instance of the
custom control to your map.
Given aHomeControlclass implementation that adheres
to the interface requirements noted above (seeCustom
Controlsdocumentation for details), the following code samples show
how to add a custom control to a map.
Overlays reflect objects that you "add" to the map to designate points,
lines, areas, or collections of objects.
Add and remove overlays
The types of objects represented
by an Overlay are the same between v2 and v3, however, they are handled
differently.
Overlays in the v2 API were added to and removed from the map using theaddOverlay()andremoveOverlay()methods of
theGMap2object. In v3, you assign a map to an Overlay using
themapproperty of the associated overlay options class.
You may also add or remove an overlay directly by calling thesetMap()method of the overlay object, and specifying the map you want. Set the map property tonullto remove the overlay.
NoclearOverlays()method exists in v3.
If you want to manage a set of overlays, you should create an array to
hold the overlays. Using this array, you can then callsetMap()on each overlay in the array (passingnullif you need to remove them).
Draggable Markers
By default, markers are clickable but not draggable. The following
two samples add a draggable marker:
You can define a custom icon to show in place of the default marker.
To use a custom image in v2, you can create aGIconinstance from theG_DEFAULT_ICON type, and modify it. If
your image is larger or smaller than the default icon, you must
specify it with aGSizeinstance.
The v3 API simplifies this process slightly.
Simply set the marker'siconproperty to the URL of your custom image, and the API will size the icon
automatically.
The Maps JavaScript API also provides support for complex icons.
A complex icon may include multiple tiles, complex shapes,
or specify the "stack order" of how the images should display relative
to other overlays. To add a shape to a marker in v2, you
need to specify the additional property in eachGIconinstance and pass this as an option
to aGMarkerconstructor. In v3, icons
specified in this manner should set theiriconproperties to an object of typeIcon.
Marker shadows are not supported in v3.
The following examples display a beach flag at Bondi Beach in
Australia, with the transparent part of the icon not clickable:
A polyline consists of an array ofLatLngs, plus a series
of line segments that connect those locations in an ordered sequence.
Creating and displaying aPolylineobject in v3 is similar
to using aGPolylineobject in v2. The following samples
draw a semi-transparent, 3-pixel wide, geodesic polyline from Zurich to
Sydney through Singapore:
No support exists in v3 for creatingPolylineobjects
directly fromencoded
polylines. Instead, theThe Geometry Libraryprovides methods to encode and decode polylines. SeeLibrariesin the v3 Maps
API for more information on how to load this library.
The examples below draw the same encoded polyline; the v3 code uses thedecodePath()method from thegoogle.maps.geometry.encodingnamespace.
A Polygon defines a region within a closed loop. Much like thePolylineobject,Polygonobjects
consist of a series of points in an ordered sequence. The v3Polygonclass is much the same as the v2GPolygonclass, with the notable exception
that you no longer have to repeat the starting vertex at the end of the
path to close the loop. The v3 API
will automatically close any polygons by drawing a stroke connecting the
last coordinate back to the first coordinate. The following code snippets
create a polygon representing the Bermuda Triangle:
For more advanced drawing capabilities, see theDrawing Libraryin the v3 documentation.
Info Windows
AnInfoWindowdisplays content in a floating window above
the map. There are a few key differences between v2 and v3 info windows:
The v2 API supports onlyGInfoWindowper map, whereas
the v3 API supports multiple, concurrentInfoWindows on
each map.
The v3InfoWindowwill remain open when you
click the map. The v2GInfoWindowcloses
automatically when you click the map. You can emulate the v2
behavior by adding aclicklistener on theMapobject.
The v3 API does not provide built-in support for a tabbedInfoWindow.
Ground Overlays
To place an image on a map, you should use aGroundOverlayobject. The constructor for aGroundOverlayis essentially the same in v2 and v3: it
specifies a URL of an image and the boundaries of the image as
parameters.
The following example places an antique map of Newark, NJ on the map
as an overlay:
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 agoogle.maps.Mapobject.
Common Map Types
The four basic map types are available in both v2 and v3:
MapTypeId.ROADMAP(replacesG_NORMAL_MAP)
displays the road map view.
MapTypeId.SATELLITE(replacesG_SATELLITE_MAP)
display Google Earth satellite images.
MapTypeId.HYBRID(replacesG_HYBRID_MAP)
displays a mixture of normal and satellite views.
MapTypeId.TERRAIN(replacesG_PHYSICAL_MAP)
displays a physical map based on terrain information.
Below is an example of v2 and v3 setting the map to terrain view:
map.setMapType(G_PHYSICAL_MAP);
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
The Maps JavaScript API v3 made a few changes to the less common map
types as well:
Map tiles forcelestial bodiesother than Earth
are not available as map types in the v3 API, but can be accessed as
custom map types. For an example, see thiscustome map types example.
There is no special map type in v3 that replaces theG_SATELLITE_3D_MAPtype from v2. Instead,
you can integrate the Google Earth plugin in your v3 maps usingthis
library.
Maximum Zoom Imagery
Satellite imagery is not always available at high zoom levels. If you may
want to know the highest zoom level available before setting the zoom level,
use thegoogle.maps.MaxZoomServiceclass. This class replaces
theGMapType.getMaxZoomAtLatLng()method from v2.
varpoint=newGLatLng(180*Math.random()-90,360*Math.random()-180);varmap=newGMap2(document.getElementById("map"));map.setUIToDefault();map.setCenter(point);map.setMapType(G_HYBRID_MAP);map.getCurrentMapType().getMaxZoomAtLatLng(point,function(response){if(response.status){map.setZoom(response.zoom);}else{alert("Error in Max Zoom Service.");}});
varmyLatlng=newgoogle.maps.LatLng(180*Math.random()-90,360*Math.random()-180);varmap=newgoogle.maps.Map(document.getElementById("map"),{zoom:0,center:myLatlng,mapTypeId:google.maps.MapTypeId.HYBRID});varmaxZoomService=newgoogle.maps.MaxZoomService();maxZoomService.getMaxZoomAtLatLng(myLatlng,function(response){if(response.status==google.maps.MaxZoomStatus.OK){map.setZoom(response.zoom);}else{alert("Error in Max Zoom Service.");}});
Aerial Perspective Imagery
When enabling Aerial imagery in v3, controls are similar to the v2GLargeZoomControl3Dcontrol, with an additional interstitial
Rotate control to rotate through supported directions.
You can track the cities where 45° imagery is available onthe supported cities map. When 45° imagery is available, a submenu option is added
to the Maps API Satellite button.
Layers
Layersare 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.
Supported Layers
The v3 API provides access to several different layers. These layers
overlap with v2GLayerclass in the following areas:
TheKmlLayerobject renders KML and GeoRSS elements into
v3 overlays, providing the equivalent for v2GeoXmllayer.
TheTrafficLayerobject renders a layer depicting
traffic conditions, similar to the v2GTrafficOverlayoverlay.
These layers are different from v2. The differences are described
below. They can be added to a map by callingsetMap(),
passing it theMapobject on which to display the
layer.
More information about supported layers is available in theLayers documentation.
KML and GeoRSS Layers
The Maps JavaScript API supports the KML and GeoRSS data formats for
displaying geographic information. The KML or GeoRSS files must be
publicly accessible if you want to include them in a map. In v3, these
data formats are displayed using an instance ofKmlLayer,
which replaces theGGeoXmlobject from v2.
The v3 API is more flexible when rendering KML, letting you
suppress InfoWindows and modify the click response. See the v3KML and GeoRSS Layersdocumentation for more detail.
When rendering aKmlLayer,
size and complexity restrictions apply; see theKmlLayer documentationfor details.
The following samples compare how to load a KML file.
In v3, you can add real-time traffic information (where supported) to your
maps using theTrafficLayerobject. Traffic information is
provided for the time that the request is made. These examples show the
traffic information for Los Angeles:
Unlike v2, no options exist for theTrafficLayerconstructor in v3. Incidents are not available in v3.
Services
Geocoding
The Maps JavaScript API provides ageocoderobject for
geocoding addresses dynamically from user input. If you want to
geocode static, known addresses, see theGeocoding APIdocumentation.
TheGeocoding APIhas been
significantly upgraded and enhanced, adding new features and changing
how data is represented.
GClientGeocoderin the v2 API provided two different methods
for forward and reverse geocoding as well as additional methods to
influence how geocoding was performed. In contrast, the v3Geocoderobject provides only ageocode()method, which takes an object literal containing the input terms
(in the form of aGeocoding
Requestsobject) and a callback method. Depending on whether the
request contains a textualaddressattribute or aLatLngobject, the Geocoding API will return a forward or
reverse geocoding response. You can influence how the geocoding is
performed by passing additional fields to the geocoding request:
Including a textualaddresstriggers forward geocoding,
equivalent to calling thegetLatLng()method.
Including alatLngobject triggers reverse geocoding,
equivalent to calling thegetLocations()method.
Including theboundsattribute enablesViewport
Biasing, equivalent to calling thesetViewport()method.
Including theregionattribute enablesRegion
Code Biasing, equivalent to calling thesetBaseCountryCode()method.
Geocoding
Responsesin v3 are very different from the v2 responses. The v3 API
replaces the nested structure that v2 uses with a flatter structure that
is easier to parse. Additionally, v3 responses are more detailed: each
result has a severaladdress
componentsthat help give a better idea of theresolutionof each result.
The following code takes a textual address and shows the first result
from geocoding it:
vargeocoder=newGClientGeocoder();varinfoPanel;varmap;varAccuracyDescription=['Unknown accuracy','country level accuracy','region level accuracy','sub-region level accuracy','town level accuracy','post code level accuracy','street level accuracy','intersection level accuracy','address level accuracy','premise level accuracy',];functiongeocode_result_handler(response){if(!response||response.Status.code!=200){alert('Geocoding failed. '+response.Status.code);}else{varbounds=newGLatLngBounds(newGLatLng(response.Placemark[0].ExtendedData.LatLonBox.south,response.Placemark[0].ExtendedData.LatLonBox.west),newGLatLng(response.Placemark[0].ExtendedData.LatLonBox.north,response.Placemark[0].ExtendedData.LatLonBox.east));map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));varlatlng=newGLatLng(response.Placemark[0].Point.coordinates[1],response.Placemark[0].Point.coordinates[0]);infoPanel.innerHTML+='<p>1st result is <em>'+// No info about location typeresponse.Placemark[0].address+'</em> of <em>'+AccuracyDescription[response.Placemark[0].AddressDetails.Accuracy]+'</em> at <tt>'+latlng+'</tt></p>';varmarker_title=response.Placemark[0].address+' at '+latlng;map.clearOverlays();varmarker=marker=newGMarker(latlng,{'title':marker_title});map.addOverlay(marker);}}functiongeocode_address(){varaddress=document.getElementById('input-text').value;infoPanel.innerHTML='<p>Original address: '+address+'</p>';geocoder.getLocations(address,geocode_result_handler);}functioninitialize(){map=newGMap2(document.getElementById('map'));map.setCenter(newGLatLng(38,15),2);map.setUIToDefault();infoPanel=document.getElementById('info-panel');}
vargeocoder=newgoogle.maps.Geocoder();varinfoPanel;varmap;varmarker;functiongeocode_result_handler(result,status){if(status!=google.maps.GeocoderStatus.OK){alert('Geocoding failed. '+status);}else{map.fitBounds(result[0].geometry.viewport);infoPanel.innerHTML+='<p>1st result for geocoding is <em>'+result[0].geometry.location_type.toLowerCase()+'</em> to <em>'+result[0].formatted_address+'</em> of types <em>'+result[0].types.join('</em>, <em>').replace(/_/,' ')+'</em> at <tt>'+result[0].geometry.location+'</tt></p>';varmarker_title=result[0].formatted_address+' at '+latlng;if(marker){marker.setPosition(result[0].geometry.location);marker.setTitle(marker_title);}else{marker=newgoogle.maps.Marker({position:result[0].geometry.location,title:marker_title,map:map});}}}functiongeocode_address(){varaddress=document.getElementById('input-text').value;infoPanel.innerHTML='<p>Original address: '+address+'</p>';geocoder.geocode({'address':address},geocode_result_handler);}functioninitialize(){map=newgoogle.maps.Map(document.getElementById('map'),{center:newgoogle.maps.LatLng(38,15),zoom:2,mapTypeId:google.maps.MapTypeId.HYBRID});infoPanel=document.getElementById('info-panel');}
Directions
The Maps JavaScript API v3 replaces theGDirectionsclass from v2 with theDirectionsServiceclass for
calculating directions.
Theroute()method in v3 replaces both theload()andloadFromWaypoints()methods from the
v2 API. This method takes a singleDirectionsRequestobject
literal containing the input terms and a callback method to execute upon
receipt of the response. Options may be given in this object literal,
similar to theGDirectionsOptionsobject literal in v2.
In the Maps JavaScript API v3, the task of submitting direction
requests has been separated from the task of rendering requests, which is
now handled with theDirectionsRendererclass. You can tie aDirectionsRendererobject to any map orDirectionsResultobject through itssetMap()andsetDirections()methods. Because the renderer is anMVCObject, it will detect any changes to its properties and
update the map when the associated directions have changed.
The following code demonstrates how to request walking directions to a
specific location using pedestrian paths from an address. Note that only
v3 is able to provide walking directions in the pedestrian path at
Dublin's Zoo.
Google Street View provides interactive, 360° views from
designated locations within its coverage area. The v3 API supports
Street View natively within the browser, unlike v2 which required
the Flash® plugin to display Street View imagery.
Street View images are supported through use of theStreetViewPanoramaobject in v3, or theGStreetviewPanoramaobject in v2. These classes have
different interfaces, but they play the same role: connecting thedivcontainer with the Street View imagery and letting
you specify the location and POV (point of view) of the Street View
panorama.
functioninitialize(){varfenwayPark=newGLatLng(42.345573,-71.098326);panoramaOptions={latlng:fenwayPark,pov:{heading:35,pitch:5,zoom:1}};varpanorama=newGStreetviewPanorama(document.getElementById('pano'),panoramaOptions);GEvent.addListener(myPano,"error",handleNoFlash);}functionhandleNoFlash(errorCode){if(errorCode==FLASH_UNAVAILABLE){alert('Error: Your browser does not support Flash');return;}}
Direct access to Street View data is possible through theStreetViewServiceobject in v3 or the similarGStreetviewClientobject in v2. Both provide similar
interfaces to retrieve or check availability of Street View data, and
allowing search by location or panorama ID.
In v3, Street View is enabled by default. The map will appear with a
Street View Pegman control and the API will reuse the map div to display
StreetView panoramas. The following code illustrates how to emulate the
v2 behavior by separating the Street View panoramas into a separate div.
varmarker;varpanoClient=newGStreetviewClient();functioninitialize(){if(GBrowserIsCompatible()){varmyPano=newGStreetviewPanorama(document.getElementById('pano'));GEvent.addListener(myPano,'error',handleNoFlash);varmap=newGMap2(document.getElementById('map'));map.setCenter(newGLatLng(42.345573,-71.098326),16);map.setUIToDefault();GEvent.addListener(map,'click',function(overlay,latlng){if(marker){marker.setLatLng(latlng);}else{marker=newGMarker(latlng);map.addOverlay(marker);}varnearestPano=panoClient.getNearestPanorama(latlng,processSVData);});functionprocessSVData(panoData){if(panoData.code!=200){alert("Panorama data not found for this location.");}varlatlng=marker.getLatLng();vardLat=latlng.latRadians()-panoData.location.latlng.latRadians();vardLon=latlng.lngRadians()-panoData.location.latlng.lngRadians();vary=Math.sin(dLon)*Math.cos(latlng.latRadians());varx=Math.cos(panoData.location.latlng.latRadians())*Math.sin(latlng.latRadians())-Math.sin(panoData.location.latlng.latRadians())*Math.cos(latlng.latRadians())*Math.cos(dLon);varbearing=Math.atan2(y,x)*180/Math.PI;myPano.setLocationAndPOV(panoData.location.latlng,{yaw:bearing});}functionhandleNoFlash(errorCode){if(errorCode==FLASH_UNAVAILABLE){alert('Error: Your browser does not support Flash');return;}}}}
// Load the API with libraries=geometryvarmap;varmarker;varpanorama;varsv=newgoogle.maps.StreetViewService();functionradians(degrees){returnMath.PI*degrees/180.0};functioninitialize(){panorama=newgoogle.maps.StreetViewPanorama(document.getElementById("pano"));map=newgoogle.maps.Map(document.getElementById('map'),{center:newgoogle.maps.LatLng(42.345573,-71.098326),mapTypeId:google.maps.MapTypeId.ROADMAP,zoom:16});google.maps.event.addListener(map,'click',function(event){if(!marker){marker=newgoogle.maps.Marker({position:event.latLng,map:map});}else{marker.setPosition(event.latLng);}sv.getPanoramaByLocation(event.latLng,50,processSVData);});}functionprocessSVData(panoData,status){if(status==google.maps.StreetViewStatus.OK){alert("Panorama data not found for this location.");}varbearing=google.maps.geometry.spherical.computeHeading(panoData.location.latLng,marker.getPosition());panorama.setPano(panoData.location.pano);panorama.setPov({heading:bearing,pitch:0,zoom:1});panorama.setVisible(true);marker.setMap(panorama);}
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-11-14 UTC."],[],["The v2 Maps JavaScript API is discontinued, requiring migration to v3. Key actions include obtaining a new API key and updating the API loading code. Code must be updated to use the `google.maps.*` namespace, removing obsolete methods. V3 offers a lighter core, improved performance, new features like styled maps and enhanced directions, multiple InfoWindows, and modern browser support. V3 also changes the way the controls, overlays, Geocoding, Directions and Streetview work, requiring code adaptations.\n"]]