- Overview
- Loading the visualization library
- Configuring API access to your layers
- The layer constructor
- Layer options
- Events
- Retrieving feature information from Google Maps Engine
- Getting and setting feature styles
- Authentication in the Maps Engine Layer
Overview
Note: The MapsEngineLayer and DynamicMapsEngineLayer classes replace the
deprecated MapDataLayer class. The MapDataLayer class was removed
from the release version of the API as of August 15, 2013.
The Google Maps visualization library provides access to the MapsEngineLayer
and the (experimental) DynamicMapsEngineLayer classes, allowing you to import
Google Maps Engine
vector data into your Google Maps JavaScript API v3 applications. These classes
give you the power to visualize and interact with Google Maps Engine data that
you own, that has been shared with you, or that is public.
The
MapsEngineLayerconstructs tiles server-side and returns the tiles to the client. Use this class if you don’t want to re-style the Maps Engine data on the client side.The
DynamicMapsEngineLayer(experimental) returns vector data to your client, along with the base map tiles. Your application can change the vectors’ styling in response to user input or other triggers. (TheDynamicMapsEngineLayerclass is not supported in Internet Explorer 8 and below.)Roll over the polygons below.
Either layer can use OAuth 2.0 authentication to access protected Maps Engine data. Users who sign into your application have the same permissions on maps and layers as through the Google Maps Engine web interface.
Loading the visualization library
The Maps Engine Layer classes are contained within the Google Maps API’s
visualization library. In order to create a Maps Engine layer,
you must load the library when loading the Maps API JavaScript:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization&key;=YOUR_API_KEY"> </script>
Google Maps API for Work developers must use a `client` parameter in place of the `key` parameter shown in the example above. Please refer to Loading the Google Maps JavaScript API for instructions specific to Maps API for Work customers.
Configuring API access to your layers
API access to Maps Engine data is controlled through access control lists in the Google Maps Engine UI. Access can be set in two different ways:
- Using the map’s settings. If you’re specifying a layer by its
mapIdandlayerKey, the map’s access control list applies to the map’s layers. - Using the layer’s API access setting. When specifying a layer using its
layerId, the layer’s API access setting controls access.
To learn about creating access control lists and applying them to maps and layers, please refer to the Google Maps Engine help center.
The layer constructor
A layer is created by constructing a MapsEngineLayer or
DynamicMapsEngineLayer object.
MapsEngineLayer:
var layer = new google.maps.visualization.MapsEngineLayer({ options });
DynamicMapsEngineLayer:
var dynamicLayer = new google.maps.visualization.DynamicMapsEngineLayer({ options });
To add a Maps Engine layer to your map, construct the object, passing a reference to your map object, and either:
A
layerId. (This is the recommended method.) View an example.var map; function initialize() { var mapOptions = { center: new google.maps.LatLng(42, -99), zoom: 5 }; map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); var dynamicLayer = new google.maps.visualization.DynamicMapsEngineLayer({ layerId: '10446176163891957399-12677872887550376890', map: map }); } google.maps.event.addDomListener(window, 'load', initialize);To find the
layerIdin the Google Maps Engine web interface:- Click the Layers link from the left-hand navigation.
- Select the desired layer from the list. The layer is displayed on the page.
- Click the Access Links icon at the top right of the screen. You will see the Asset ID of the layer.
Or, a
mapIdand alayerKey. View an example.var map; function initialize() { var mapOptions = { center: new google.maps.LatLng(42, -99), zoom: 5 }; map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); var layer = new google.maps.visualization.MapsEngineLayer({ mapId: '10446176163891957399-13516001307527776624', layerKey: 'layer_00001', map: map }); } google.maps.event.addDomListener(window, 'load', initialize);To find the
mapIdandlayerKeyvalues in the Google Maps Engine web interface:- Click the Maps link from the left-hand navigation.
- Select the desired map from the list. The map is displayed on the page.
- Click the Access Links icon at the top right of the screen, then click API access. You will see the Asset ID of the map, as well as the layer name and layer key.
Layer options
The layer constructor accepts the following options:
mapIdis used withlayerKey, and specifies the map to which the layer belongs. Layer keys are only unique within a map. To find a map’s ID, click the Access Links icon at the top right of the map page, then click API access. You will see the Asset ID of the map, as well as the layer name and layer key.layerKeyspecifies the map layer to load. AmapIdis also required when usinglayerKey. Click the Access Links icon at the top right of the map page, then click API access to see the layer key for each of your map’s layers. Up to 15 layers can be loaded on a map; create and add a newMapsEngineLayerobject for each layer.layerIdspecifies a layer to load using its globally-unique ID. When specifying a layer by its ID, nomapIdis required. To find thelayerIdin the Maps Engine web interface, navigate to the specific Layer Details page, and click the Access Links icon at the top right.mapspecifies thegoogle.maps.Mapobject to which the layer is to be attached.clickableaccepts a true or false value, and specifies whether the layer will receive mouse events. The default value istrue.suppressInfoWindowsaccepts a true or false value; if set totrueinfo windows are not displayed when layer features are clicked.accessTokenaccepts the authentication token returned by an OAuth 2.0 authentication request. For more information, please read the Authentication in the Maps Engine Layer section of this document.
If your map is public, no additional steps are required. If your map is private, you’ll need to provide authentication credentials.
Events
The MapsEngineLayer and DynamicMapsEngineLayer classes support various events.
MapsEngineLayer events
The MapsEngineLayer fires the following events:
clickis fired when a feature in the layer is clicked. It passes aMapsEngineMouseEventobject with the following properties:featureIdis the feature’s Google Maps Engine ID.infoWindowHtmlis a string containing the default info window content.latLngis agoogle.maps.LatLngobject, specifying the location of the point if the feature is a point, or the actual click location if the feature is a polyline or polygon.pixelOffsetis agoogle.maps.Sizeobject, defining the offset at which to place an infowindow to correctly anchor it to this feature.
properties_changedis fired when the layer has finished loading, and the layer’s properties are available for reading. No event object is passed.status_changedis fired when the layer has finished loading, and the status is available to determine whether the layer loaded. No event object is passed.
DynamicMapsEngineLayer events
The DynamicMapsEngineLayer fires the following events.
Mouse events:
mousemovemouseupmousedownmouseovermouseoutclickdblclickrightclick
Each passes a DynamicMapsEngineMouseEvent object with the
following properties:
featureIdis the feature’s Google Maps Engine ID.latLngis agoogle.maps.LatLngobject, specifying point if the feature is a point, or the actual click location if the feature is a polyline or polygon.
The DynamicMapsEngineMouseEvent object also contains the following function:
getDetails()accepts a callback function, to which is passed aMapsEngineMouseEventobject with additional details about the event.
Load events:
properties_changedis fired when the layer has finished loading, and the layer’s properties are available for reading. No event object is passed.status_changedis fired when the layer has finished loading, and the status is available to determine whether the layer loaded. No event object is passed.
Listening for events
To capture an event, set a listener on the layer:
google.maps.event.addListener(layer, 'click', function(event) {
var infoWindowContent = event.infoWindowHtml;
});
Retrieving feature information from Google Maps Engine
The featureId property of the MapsEngineMouseEvent and
DynamicMapsEngineMouseEvent objects identifies a feature in a Google Maps
Engine project. You can retrieve information about the feature using the
Google Maps Engine API.
Accessing public data in the Google
Maps Engine developer’s guide provides more information.
Getting and setting feature styles
The DynamicMapsEngineLayer supports getting and setting feature styles. To
retrieve a feature’s style, call getFeatureStyle(), passing the feature’s
ID as a string:
var style = dynamicLayer.getFeatureStyle('1234');
To set a style, you can access any of the FeatureStyle object’s properties:
fillColorandfillOpacitystrokeColor,strokeOpacity, andstrokeWidthiconImage,iconClip,iconAnchor,iconSize, andiconOpacityzIndex
DynamicMapsEngineLayer supports only selected Maps Engine feature styles as documented in this comparison table. Unsupported styles cannot be displayed or changed.
Supported properties are described in the FeatureStyle reference.
For example:
var style = dynamicLayer.getFeatureStyle('1234');
style.strokeColor = '#FF0000';
style.iconImage = 'url(images/myIcon.png)';
An example of changing the style on mouseover:
google.maps.event.addListener(dynamicLayer, 'mouseover', function(e) {
var style = dynamicLayer.getFeatureStyle(e.featureId);
style.strokeColor = 'red';
style.zIndex = 1000;
});
Resetting a style
To remove all styling from a feature and return it to the style in which it
was originally passed, call resetAll() on the FeatureStyle object:
dynamicLayer.getFeatureStyle('1234').resetAll();
You can also reset a specific property by calling reset() on the FeatureStyle
object:
dynamicLayer.getFeatureStyle('1234').reset('strokeColor');
Authentication in the Maps Engine Layer
Users can authenticate to your map using their Google Account, if you’ve granted them access in Google Maps Engine. Authentication in Maps Engine layers uses an OAuth 2.0 token; for information, please refer to the OAuth 2.0 documentation.
An example of obtaining an OAuth 2.0 token using the Google API Javascript Auth Library (Beta) is below. Before you begin, you must have:
- A Client ID for web applications, obtained from the API Access page
of the
Google Developers Console. It
is of the form
STRING.apps.googleusercontent.com. - A valid redirect URI, also configured in the APIs Console. By default
when creating a new client ID, the redirect URL is
https://YOUR_DOMAIN/oauth2callback. In the example below, it’s assumed that the redirect URI has been edited to be the same value as the application’s URI (i.e. the authentication process will return the user to the originating page once authentication is complete). Click Edit settings… from the API Access page to change your redirect URI. - The OAuth scope, which is
https://www.googleapis.com/auth/mapsengine.readonly. This is the only supported scope. If your application is using themapsenginescope (not.readonly) for accessing Google Maps Engine data, you must also include themapsengine.readonlyscope for use with a Maps Engine Layer.
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization"></script>
<script src="https://apis.google.com/js/auth.js"></script>
<script type="text/javascript">
// An example of how to use oauth to obtain authorization for a web application
// to display Maps Engine layers readable by a user of that application.
//
// The application follows the following flow:
// 1. When first loaded, the application checks if the user has already
// authorized this application. If so, a function is called to display
// the requested layer. This check is asynchronous, so uses callbacks in
// JavaScript. If the user has authorized the application, an access_token
// is granted by oauth, which can be used to authenticate when displaying
// a Maps Engine Layer.
//
// 2. If the user has not authorized this application, an 'Authorize' button
// is shown in the UI. An oauth flow is started when the user clicks this
// button. Within this flow, the user is asked if they will grant permission
// for this application to be able to read their Maps Engine data so that
// it can be displayed on a Map.
//
// 3. If the user grants authorization to the application, the 'Authorize'
// button is hidden and the Layer is shown. If not the 'Authorize' button
// remains visible.
//
// 4. Periodically, the access_token is refreshed by making another call to the
// oauth library.
// The Client ID for your application, as configured on the Google APIs console.
var clientId = 'PLACE YOUR CLIENT ID HERE';
// The oauth scope for displaying Maps Engine data.
var scopes = 'https://www.googleapis.com/auth/mapsengine.readonly';
// The Asset ID of the Maps Engine Layer to display.
var layerId = 'PLACE YOUR LAYER ID HERE';
// This function is run when the page (including the Maps API and Google APIs
// client libraries) have finished loading.
function initialize() {
checkAuth(false, handleAuthResult);
}
// A shared function which checks if the user has previously authorized this
// application, and if so calls the supplied callback.
// This function should always be called before calling a function which
// requires an oauth access_token.
//
// If prompt_user is true, the user will be prompted to provide access. This
// should not be set to true unless this function was triggered by a user
// action (e.g. clicking a button).
//
// If prompt_user is set to false, and the user is not authorized, the callback
// will be called with null.
function checkAuth(prompt_user, callback) {
var options = {
client_id: clientId,
scope: scopes,
// Setting immediate to 'true' will avoid prompting the user for
// authorization if they have already granted it in the past.
immediate: !prompt_user
}
// Check to see if the current user has authorized this application.
gapi.auth.authorize(options, callback);
}
// A callback run after checking if the user has authorized this application.
// If they have not, then authResult will be null, and a button will be
// displayed which the user can click to begin authorization.
//
// Authorization can only be started in response to a user action (such as
// clicking a button) in order to avoid triggering popup blockers.
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize_button');
// Has the user authorized this application?
if (authResult && !authResult.error) {
// The application is authorized. Hide the 'Authorization' button.
authorizeButton.style.display = 'none';
showMap(authResult);
} else {
// The application has not been authorized. Start the authorization flow
// when the user clicks the button.
authorizeButton.style.display = 'block';
authorizeButton.onclick = handleAuthClick;
}
}
// This function is called when the user clicks the Authorization button. It
// starts the authorization flow.
function handleAuthClick(event) {
checkAuth(true, handleAuthResult);
return false;
}
// This function is called once handleAuthResult detects that authorization
// has been provided.
function showMap(authResult) {
// Create a new Google Maps API Map
var mapOptions = {
center: new google.maps.LatLng(0,0),
zoom: 4
};
map = new google.maps.Map(
document.getElementById("map-canvas"),
mapOptions);
// Add a Maps Engine Layer to this Map. The access_token granted by the oauth
// flow is used here to access user data.
mapsEngineLayer = new google.maps.visualization.MapsEngineLayer({
layerId: layerId,
accessToken: authResult.access_token
});
mapsEngineLayer.setMap(map);
// Add an event listener which modifies the bounds of the Map to best fit
// the Layer once the layer has loaded.
google.maps.event.addListener(mapsEngineLayer, 'bounds_changed', function() {
map.fitBounds(mapsEngineLayer.get('bounds'));
});
// The access_token provided by the oauth flow is only valid for a certain
// amount of time. Add a timer which will refresh the access_token after this
// amount of time has elapsed, so that the Layer will continue to work.
window.setTimeout(refreshToken, authResult.expires_in * 1000);
}
// This function is called once the oauth token has expired. It starts an
// oauth flow in the background which obtains a new token. The user will not
// be prompted to do anything, because we set the 'immediate' property on the
// gapi.auth.authorize request to true.
function refreshToken() {
checkAuth(false, refreshLayer);
}
// This function is called once an expired access_token has been refreshed, and
// a new access_token is available.
function refreshLayer(authResult) {
// Update the token provided to the MapsEngineLayer.
mapsEngineLayer.set('accessToken', authResult.access_token);
// This token will also expire after some time, so create a timer which will
// refresh it again.
window.setTimeout(refreshToken, authResult.expires_in * 1000);
}
</script>
</head>
<body onload="initialize()">
<input type="button" value="Authorize" id="authorize_button"
style="display: none;"></input>
<div id="map-canvas" style="height: 100%; width: 100%;">
</div>
</body>
</html>