Controls

Controls Overview

The maps displayed through the Google Maps JavaScript API contain UI elements to allow user interaction with the map. These elements are known as controls and you can include variations of these controls in your application. Alternatively, you can do nothing and let the Google Maps JavaScript API handle all control behavior.

The following map shows the default set of controls displayed by the Google Maps JavaScript API:

View example (control-default.html).

Below is a list of the full set of controls you can use in your maps:

  • The Zoom control displays "+" and "-" buttons for changing the zoom level of the map. This control appears by default in the bottom right corner of the map.
  • The Map Type control is available in a dropdown or horizontal button bar style, allowing the user to choose a map type (ROADMAP, SATELLITE, HYBRID, or TERRAIN). This control appears by default in the top left corner of the map.
  • The Street View control contains a Pegman icon which can be dragged onto the map to enable Street View. This control appears by default near the bottom right of the map.
  • The Rotate control provides a combination of tilt and rotate options for maps containing oblique imagery. This control appears by default near the bottom right of the map. See 45° imagery for more information.
  • The Scale control displays a map scale element. This control is disabled by default.
  • The Fullscreen control offers the option to open the map in fullscreen mode. This control is disabled by default.

You don't access or modify these map controls directly. Instead, you modify the map's MapOptions fields which affect the visibility and presentation of controls. You can adjust control presentation upon instantiating your map (with appropriate MapOptions) or modify a map dynamically by calling setOptions() to change the map's options.

Not all of these controls are enabled by default. To learn about default UI behavior (and how to modify such behavior), see The Default UI below.

The Default UI

By default, all the controls disappear if the map is too small (200x200px). You can override this behavior by explicitly setting the control to be visible. See Adding Controls to the Map.

The behavior and appearance of the controls is the same across mobile and desktop devices.

Additionally, keyboard handling is on by default on all devices.

Disabling the Default UI

You may wish to turn off the API's default UI settings entirely. To do so, set the map's disableDefaultUI property (within the MapOptions object) to true. This property disables any automatic UI behavior from the Google Maps JavaScript API.

The following code disables the default UI entirely:

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {lat: -33, lng: 151},
    disableDefaultUI: true
  });
}
<div id="map"></div>
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {lat: -33, lng: 151},
    disableDefaultUI: true
  });
}

View example (control-disableUI.html).

Adding Controls to the Map

You may wish to tailor your interface by removing, adding, or modifying UI behavior or controls and ensure that future updates don't alter this behavior. If you wish to only add or modify existing behavior, you need to ensure that the control is explicitly added to your application.

Some controls appear on the map by default while others will not appear unless you specifically request them. Adding or removing controls from the map is specified in the following MapOptions object's fields, which you set to true to make them visible or set to false to hide them:

{
  zoomControl: boolean,
  mapTypeControl: boolean,
  scaleControl: boolean,
  streetViewControl: boolean,
  rotateControl: boolean,
  fullscreenControl: boolean
}

By default, all the controls disappear if the map is smaller than 200x200px. You can override this behavior by explicitly setting the control to be visible. For example, the following table shows whether the zoom control is visible or not, based on the map size and the setting of the zoomControl field:

Map size zoomControl Visible?
Any false No
Any true Yes
>= 200x200px undefined Yes
< 200x200px undefined No

The following example sets the map to hide the Zoom control and display the Scale control. Note that we do not explicitly disable the default UI, so these modifications are additive to the default UI behavior.

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {lat: -33, lng: 151},
    zoomControl: false,
    scaleControl: true
  });
}
<div id="map"></div>
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {lat: -33, lng: 151},
    zoomControl: false,
    scaleControl: true
  });
}

View example (control-simple.html).

Control Options

Several controls are configurable, allowing you to alter their behavior or change their appearance. The Map Type control, for example, may appear as a horizontal bar or a dropdown menu.

These controls are modified by altering appropriate control options fields within the MapOptions object upon creation of the map.

For example, options for altering the Map Type control are indicated in the mapTypeControlOptions field. The Map Type control may appear in one of the following style options:

  • google.maps.MapTypeControlStyle.HORIZONTAL_BAR displays the array of controls as buttons in a horizontal bar as is shown on Google Maps.
  • google.maps.MapTypeControlStyle.DROPDOWN_MENU displays a single button control allowing you to select the map type via a dropdown menu.
  • google.maps.MapTypeControlStyle.DEFAULT displays the default behavior, which depends on screen size and may change in future versions of the API.

Note that if you do modify any control options, you should explicitly enable the control as well by setting the appropriate MapOptions value to true. For example, to set a Map Type control to exhibit the DROPDOWN_MENU style, use the following code within the MapOptions object:

  ...
  mapTypeControl: true,
  mapTypeControlOptions: {
    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
  }
  ...

The following example demonstrates how to change the default position and style of controls.

// You can set control options to change the default position or style of many
// of the map controls.

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {lat: -33, lng: 151},
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
      mapTypeIds: [
        google.maps.MapTypeId.ROADMAP,
        google.maps.MapTypeId.TERRAIN
      ]
    }
  });
}
<div id="map"></div>
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
// You can set control options to change the default position or style of many
// of the map controls.

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {lat: -33, lng: 151},
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
      mapTypeIds: [
        google.maps.MapTypeId.ROADMAP,
        google.maps.MapTypeId.TERRAIN
      ]
    }
  });
}

View example (control-options.html).

Controls are typically configured upon creation of the map. However, you may alter the presentation of controls dynamically by calling the Map's setOptions() method, passing it new control options.

Modifying Controls

You specify a control's presentation when you create your map through fields within the map's MapOptions object. These fields are denoted below:

  • zoomControl enables/disables the Zoom control. By default, this control is visible and appears near the bottom right of the map. The zoomControlOptions field additionally specifies the ZoomControlOptions to use for this control.
  • mapTypeControl enables/disables the Map Type control that lets the user toggle between map types (such as Map and Satellite). By default, this control is visible and appears in the top left corner of the map. The mapTypeControlOptions field additionally specifies the MapTypeControlOptions to use for this control.
  • streetViewControl enables/disables the Pegman control that lets the user activate a Street View panorama. By default, this control is visible and appears near the bottom right of the map. The streetViewControlOptions field additionally specifies the StreetViewControlOptions to use for this control.
  • rotateControl enables/disables the appearance of a Rotate control for controlling the orientation of 45° imagery. By default, the control's presence is determined by the presence or absence of 45° imagery for the given map type at the current zoom and location. You may alter the control's behavior by setting the map's rotateControlOptions to specify the RotateControlOptions to use. You cannot make the control appear if no 45° imagery is currently available.
  • scaleControl enables/disables the Scale control that provides a simple map scale. By default, this control is not visible. When enabled, it will always appear in the bottom right corner of the map. The scaleControlOptions additionally specifies the ScaleControlOptions to use for this control.
  • fullscreenControl enables/disables the control that opens the map in fullscreen mode. By default, this control is not visible. When enabled, it appears near the top right of the map. The fullscreenControlOptions additionally specifies the FullscreenControlControlOptions to use for this control.

Note that you may specify options for controls you initially disable.

Control Positioning

Most of the control options contain a position property (of type ControlPosition) which indicates where on the map to place the control. Positioning of these controls is not absolute. Instead, the API will lay out the controls intelligently by flowing them around existing map elements, or other controls, within given constraints (such as the map size).

Note: No guarantees can be made that controls may not overlap given complicated layouts, though the API will attempt to arrange them intelligently.

The following control positions are supported:

  • TOP_CENTER indicates that the control should be placed along the top center of the map.
  • TOP_LEFT indicates that the control should be placed along the top left of the map, with any sub-elements of the control "flowing" towards the top center.
  • TOP_RIGHT indicates that the control should be placed along the top right of the map, with any sub-elements of the control "flowing" towards the top center.
  • LEFT_TOP indicates that the control should be placed along the top left of the map, but below any TOP_LEFT elements.
  • RIGHT_TOP indicates that the control should be placed along the top right of the map, but below any TOP_RIGHT elements.
  • LEFT_CENTER indicates that the control should be placed along the left side of the map, centered between the TOP_LEFT and BOTTOM_LEFT positions.
  • RIGHT_CENTER indicates that the control should be placed along the right side of the map, centered between the TOP_RIGHT and BOTTOM_RIGHT positions.
  • LEFT_BOTTOM indicates that the control should be placed along the bottom left of the map, but above any BOTTOM_LEFT elements.
  • RIGHT_BOTTOM indicates that the control should be placed along the bottom right of the map, but above any BOTTOM_RIGHT elements.
  • BOTTOM_CENTER indicates that the control should be placed along the bottom center of the map.
  • BOTTOM_LEFT indicates that the control should be placed along the bottom left of the map, with any sub-elements of the control "flowing" towards the bottom center.
  • BOTTOM_RIGHT indicates that the control should be placed along the bottom right of the map, with any sub-elements of the control "flowing" towards the bottom center.

View example (control-positioning-labels.html).

Note that these positions may coincide with positions of UI elements whose placements you may not modify (such as copyrights and the Google logo). In those cases, the controls will flow according to the logic noted for each position and appear as close as possible to their indicated position.

The following example shows a simple map with all controls enabled, in different positions.

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: {lat: -28.643387, lng: 153.612224},
    mapTypeControl: true,
    mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
        position: google.maps.ControlPosition.TOP_CENTER
    },
    zoomControl: true,
    zoomControlOptions: {
        position: google.maps.ControlPosition.LEFT_CENTER
    },
    scaleControl: true,
    streetViewControl: true,
    streetViewControlOptions: {
        position: google.maps.ControlPosition.LEFT_TOP
    },
    fullscreenControl: true
  });
}
<div id="map"></div>
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: {lat: -28.643387, lng: 153.612224},
    mapTypeControl: true,
    mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
        position: google.maps.ControlPosition.TOP_CENTER
    },
    zoomControl: true,
    zoomControlOptions: {
        position: google.maps.ControlPosition.LEFT_CENTER
    },
    scaleControl: true,
    streetViewControl: true,
    streetViewControlOptions: {
        position: google.maps.ControlPosition.LEFT_TOP
    },
    fullscreenControl: true
  });
}

View example (control-positioning.html).

Custom Controls

As well as modifying the style and position of existing API controls, you can create your own controls to handle interaction with the user. Controls are stationary widgets which float on top of a map at absolute positions, as opposed to overlays, which move with the underlying map. More fundamentally, a control is simply a <div> element which has an absolute position on the map, displays some UI to the user, and handles interaction with either the user or the map, usually through an event handler.

To create your own custom control, few rules are necessary. However, the following guidelines can act as best practice:

  • Define appropriate CSS for the control element(s) to display.
  • Handle interaction with the user or the map through event handlers for either map property changes or user events (for example, 'click' events).
  • Create a <div> element to hold the control and add this element to the Map's controls property.

Each of these concerns is discussed below.

Drawing Custom Controls

How you draw your control is up to you. Generally, we recommend that you place all of your control presentation within a single <div> element so that you can manipulate your control as one unit. We will use this design pattern in the samples shown below.

Designing attractive controls requires some knowledge of CSS and DOM structure. The following code shows how a simple control is created from a containing <div>, a <div> to hold the button outline, and another <div> to hold the button interior.

// Create a div to hold the control.
var controlDiv = document.createElement('div');

// Set CSS for the control border
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = '#fff';
controlUI.style.border = '2px solid #fff';
controlUI.style.cursor = 'pointer';
controlUI.style.marginBottom = '22px';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to recenter the map';
controlDiv.appendChild(controlUI);

// Set CSS for the control interior
var controlText = document.createElement('div');
controlText.style.color = 'rgb(25,25,25)';
controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
controlText.style.fontSize = '16px';
controlText.style.lineHeight = '38px';
controlText.style.paddingLeft = '5px';
controlText.style.paddingRight = '5px';
controlText.innerHTML = 'Center Map';
controlUI.appendChild(controlText);

Handling Events from Custom Controls

For a control to be useful, it must actually do something. What the control does is up to you. The control may respond to user input, or it may respond to changes in the Map's state.

For responding to user input, the Google Maps JavaScript API provides a cross-browser event handling method addDomListener() which handles most of the browser's supported DOM events. The following code snippet adds a listener for the browser's 'click' event. Note that this event is received from the DOM, not from the map.

// Setup the click event listener: simply set the map to center on Chicago
var chicago = {lat: 41.850, lng: -87.650};

google.maps.event.addDomListener(outer, 'click', function() {
  map.setCenter(chicago)
});

Positioning Custom Controls

Custom controls are positioned on the map by placing them at appropriate positions within the Map object's controls property. This property contains an array of google.maps.ControlPositions. You add a custom control to the map by adding the Node (typically the <div>) to an appropriate ControlPosition. (For information on these positions, see Control Positioning above.)

Each ControlPosition stores an MVCArray of the controls displayed in that position. As a result, when controls are added or removed from the position, the API will update the controls accordingly.

The API places controls at each position by the order of an index property; controls with a lower index are placed first. For example, two custom controls at position BOTTOM_RIGHT will be laid out according to this index order, with lower index values taking precedence. By default, all custom controls are placed after placing any API default controls. You can override this behavior by setting a control's index property to be a negative value. Custom controls cannot be placed to the left of the logo or to the right of the copyrights.

The following code creates a new custom control (its constructor is not shown) and adds it to the map in the TOP_RIGHT position.

var map = new google.maps.Map(document.getElementById('map'), mapOptions);

// Construct your control in whatever manner is appropriate.
// Generally, your constructor will want access to the
// DIV on which you'll attach the control UI to the Map.
var controlDiv = document.createElement('div');
var myControl = new MyControl(controlDiv);

// We don't really need to set an index value here, but
// this would be how you do it. Note that we set this
// value as a property of the DIV itself.
controlDiv.index = 1;

// Add the control to the map at a designated control position
// by pushing it on the position's array. This code will
// implicitly add the control to the DOM, through the Map
// object. You should not attach the control manually.
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);

A Custom Control Example

The following control is simple (though not particularly useful) and combines the patterns shown above. This control responds to DOM 'click' events by centering the map at a certain default location:

var map;
var chicago = {lat: 41.85, lng: -87.65};

/**
 * The CenterControl adds a control to the map that recenters the map on
 * Chicago.
 * This constructor takes the control DIV as an argument.
 * @constructor
 */
function CenterControl(controlDiv, map) {

  // Set CSS for the control border.
  var controlUI = document.createElement('div');
  controlUI.style.backgroundColor = '#fff';
  controlUI.style.border = '2px solid #fff';
  controlUI.style.borderRadius = '3px';
  controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
  controlUI.style.cursor = 'pointer';
  controlUI.style.marginBottom = '22px';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Click to recenter the map';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior.
  var controlText = document.createElement('div');
  controlText.style.color = 'rgb(25,25,25)';
  controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
  controlText.style.fontSize = '16px';
  controlText.style.lineHeight = '38px';
  controlText.style.paddingLeft = '5px';
  controlText.style.paddingRight = '5px';
  controlText.innerHTML = 'Center Map';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to Chicago.
  controlUI.addEventListener('click', function() {
    map.setCenter(chicago);
  });

}

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: chicago
  });

  // Create the DIV to hold the control and call the CenterControl()
  // constructor passing in this DIV.
  var centerControlDiv = document.createElement('div');
  var centerControl = new CenterControl(centerControlDiv, map);

  centerControlDiv.index = 1;
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);
}
<div id="map"></div>
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
var map;
var chicago = {lat: 41.85, lng: -87.65};

/**
 * The CenterControl adds a control to the map that recenters the map on
 * Chicago.
 * This constructor takes the control DIV as an argument.
 * @constructor
 */
function CenterControl(controlDiv, map) {

  // Set CSS for the control border.
  var controlUI = document.createElement('div');
  controlUI.style.backgroundColor = '#fff';
  controlUI.style.border = '2px solid #fff';
  controlUI.style.borderRadius = '3px';
  controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
  controlUI.style.cursor = 'pointer';
  controlUI.style.marginBottom = '22px';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Click to recenter the map';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior.
  var controlText = document.createElement('div');
  controlText.style.color = 'rgb(25,25,25)';
  controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
  controlText.style.fontSize = '16px';
  controlText.style.lineHeight = '38px';
  controlText.style.paddingLeft = '5px';
  controlText.style.paddingRight = '5px';
  controlText.innerHTML = 'Center Map';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to Chicago.
  controlUI.addEventListener('click', function() {
    map.setCenter(chicago);
  });

}

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: chicago
  });

  // Create the DIV to hold the control and call the CenterControl()
  // constructor passing in this DIV.
  var centerControlDiv = document.createElement('div');
  var centerControl = new CenterControl(centerControlDiv, map);

  centerControlDiv.index = 1;
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);
}

View example (control-custom.html).

Adding State to Controls

Controls may also store state. The following example is similar to that shown before, but the control contains an additional "Set Home" button which sets the control to exhibit a new home location. We do so by creating a home_ property within the control to store this state and provide getters and setters for that state.

var map;
var chicago = {lat: 41.85, lng: -87.65};

/**
 * The CenterControl adds a control to the map that recenters the map on
 * Chicago.
 * @constructor
 * @param {!Element} controlDiv
 * @param {!google.maps.Map} map
 * @param {?google.maps.LatLng} center
 */
function CenterControl(controlDiv, map, center) {
  // We set up a variable for this since we're adding event listeners
  // later.
  var control = this;

  // Set the center property upon construction
  control.center_ = center;
  controlDiv.style.clear = 'both';

  // Set CSS for the control border
  var goCenterUI = document.createElement('div');
  goCenterUI.id = 'goCenterUI';
  goCenterUI.title = 'Click to recenter the map';
  controlDiv.appendChild(goCenterUI);

  // Set CSS for the control interior
  var goCenterText = document.createElement('div');
  goCenterText.id = 'goCenterText';
  goCenterText.innerHTML = 'Center Map';
  goCenterUI.appendChild(goCenterText);

  // Set CSS for the setCenter control border
  var setCenterUI = document.createElement('div');
  setCenterUI.id = 'setCenterUI';
  setCenterUI.title = 'Click to change the center of the map';
  controlDiv.appendChild(setCenterUI);

  // Set CSS for the control interior
  var setCenterText = document.createElement('div');
  setCenterText.id = 'setCenterText';
  setCenterText.innerHTML = 'Set Center';
  setCenterUI.appendChild(setCenterText);

  // Set up the click event listener for 'Center Map': Set the center of
  // the map
  // to the current center of the control.
  goCenterUI.addEventListener('click', function() {
    var currentCenter = control.getCenter();
    map.setCenter(currentCenter);
  });

  // Set up the click event listener for 'Set Center': Set the center of
  // the control to the current center of the map.
  setCenterUI.addEventListener('click', function() {
    var newCenter = map.getCenter();
    control.setCenter(newCenter);
  });
}

/**
 * Define a property to hold the center state.
 * @private
 */
CenterControl.prototype.center_ = null;

/**
 * Gets the map center.
 * @return {?google.maps.LatLng}
 */
CenterControl.prototype.getCenter = function() {
  return this.center_;
};

/**
 * Sets the map center.
 * @param {?google.maps.LatLng} center
 */
CenterControl.prototype.setCenter = function(center) {
  this.center_ = center;
};

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: chicago
  });

  // Create the DIV to hold the control and call the CenterControl()
  // constructor
  // passing in this DIV.
  var centerControlDiv = document.createElement('div');
  var centerControl = new CenterControl(centerControlDiv, map, chicago);

  centerControlDiv.index = 1;
  centerControlDiv.style['padding-top'] = '10px';
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);
}
<div id="map"></div>
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
#goCenterUI, #setCenterUI {
  background-color: #fff;
  border: 2px solid #fff;
  border-radius: 3px;
  box-shadow: 0 2px 6px rgba(0,0,0,.3);
  cursor: pointer;
  float: left;
  margin-bottom: 22px;
  text-align: center;
}
#goCenterText, #setCenterText {
  color: rgb(25,25,25);
  font-family: Roboto,Arial,sans-serif;
  font-size: 15px;
  line-height: 25px;
  padding-left: 5px;
  padding-right: 5px;
}
#setCenterUI {
  margin-left: 12px;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
var map;
var chicago = {lat: 41.85, lng: -87.65};

/**
 * The CenterControl adds a control to the map that recenters the map on
 * Chicago.
 * @constructor
 * @param {!Element} controlDiv
 * @param {!google.maps.Map} map
 * @param {?google.maps.LatLng} center
 */
function CenterControl(controlDiv, map, center) {
  // We set up a variable for this since we're adding event listeners
  // later.
  var control = this;

  // Set the center property upon construction
  control.center_ = center;
  controlDiv.style.clear = 'both';

  // Set CSS for the control border
  var goCenterUI = document.createElement('div');
  goCenterUI.id = 'goCenterUI';
  goCenterUI.title = 'Click to recenter the map';
  controlDiv.appendChild(goCenterUI);

  // Set CSS for the control interior
  var goCenterText = document.createElement('div');
  goCenterText.id = 'goCenterText';
  goCenterText.innerHTML = 'Center Map';
  goCenterUI.appendChild(goCenterText);

  // Set CSS for the setCenter control border
  var setCenterUI = document.createElement('div');
  setCenterUI.id = 'setCenterUI';
  setCenterUI.title = 'Click to change the center of the map';
  controlDiv.appendChild(setCenterUI);

  // Set CSS for the control interior
  var setCenterText = document.createElement('div');
  setCenterText.id = 'setCenterText';
  setCenterText.innerHTML = 'Set Center';
  setCenterUI.appendChild(setCenterText);

  // Set up the click event listener for 'Center Map': Set the center of
  // the map
  // to the current center of the control.
  goCenterUI.addEventListener('click', function() {
    var currentCenter = control.getCenter();
    map.setCenter(currentCenter);
  });

  // Set up the click event listener for 'Set Center': Set the center of
  // the control to the current center of the map.
  setCenterUI.addEventListener('click', function() {
    var newCenter = map.getCenter();
    control.setCenter(newCenter);
  });
}

/**
 * Define a property to hold the center state.
 * @private
 */
CenterControl.prototype.center_ = null;

/**
 * Gets the map center.
 * @return {?google.maps.LatLng}
 */
CenterControl.prototype.getCenter = function() {
  return this.center_;
};

/**
 * Sets the map center.
 * @param {?google.maps.LatLng} center
 */
CenterControl.prototype.setCenter = function(center) {
  this.center_ = center;
};

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: chicago
  });

  // Create the DIV to hold the control and call the CenterControl()
  // constructor
  // passing in this DIV.
  var centerControlDiv = document.createElement('div');
  var centerControl = new CenterControl(centerControlDiv, map, chicago);

  centerControlDiv.index = 1;
  centerControlDiv.style['padding-top'] = '10px';
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);
}

View example (control-custom-state.html).

Send feedback about...

Google Maps JavaScript API
Google Maps JavaScript API
Need help? Visit our support page.