Google Maps JavaScript API v3

Maps Engine Layers

Overview

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 MapsEngineLayer constructs 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. (The DynamicMapsEngineLayer class 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="http://maps.googleapis.com/maps/api/js?libraries=visualization&key=YOUR_API_KEY&sensor=true_or_false">
</script>

Google Maps API for Business 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 Business-specific instructions.

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 mapId and layerKey, 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 layerId in the Maps Engine web interface, navigate to the specific Layer Details page and click the Asset ID link.

  • Or, a mapId and a layerKey. 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 mapId and layerKey values 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 Switch to map details view button above the map.
    • Click the Maps API ID: Details link. The map ID and layer key(s) are displayed.

Layer options

The layer constructor accepts the following options:

  • mapId is used with layerKey, 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 Map ID link from the Map Details page.
  • layerKey specifies the map layer to load. A mapId is also required when using layerKey. Click the Map ID link from the Map Details page 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 new MapsEngineLayer object for each layer.
  • layerId specifies a layer to load using its globally-unique ID. When specifying a layer by its ID, no mapId is required. To find the layerId in the Maps Engine web interface, navigate to the specific Layer Details page, and click the Asset ID link.
  • map specifies the google.maps.Map object to which the layer is to be attached.
  • clickable accepts a true or false value, and specifies whether the layer will receive mouse events. The default value is true.
  • suppressInfoWindows accepts a true or false value; if set to true info windows are not displayed when layer features are clicked.
  • accessToken accepts 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:

  • click is fired when a feature in the layer is clicked. It passes a MapsEngineMouseEvent object with the following properties:

    • featureId is the feature's Google Maps Engine ID.
    • infoWindowHtml is a string containing the default info window content.
    • latLng is a google.maps.LatLng object, 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.
    • pixelOffset is a google.maps.Size object, defining the offset at which to place an infowindow to correctly anchor it to this feature.
  • properties_changed is fired when the layer has finished loading, and the layer's properties are available for reading. No event object is passed.
  • status_changed is 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:

  • mousemove
  • mouseup
  • mousedown
  • mouseover
  • mouseout
  • click
  • dblclick
  • rightclick

Each passes a DynamicMapsEngineMouseEvent object with the following properties:

  • featureId is the feature's Google Maps Engine ID.
  • latLng is a google.maps.LatLng object, 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:

Load events:

  • properties_changed is fired when the layer has finished loading, and the layer's properties are available for reading. No event object is passed.
  • status_changed is 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:

  • fillColor and fillOpacity
  • strokeColor, strokeOpacity, and strokeWidth
  • iconImage, iconClip, iconAnchor, iconSize, and iconOpacity
  • zIndex

These 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 APIs 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 the mapsengine scope (not .readonly) for accessing Google Maps Engine data, you must also include the mapsengine.readonly scope for use with a Maps Engine Layer.
<html>
<head>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=visualization&sensor=false"></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>

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.