Skip to main content

Map

The Map object is used to display the Google map.

Map extends Evented.

Example usage​

See the Display the map tutorial page for more information.

<div id="map"></div>
<script>
const map = G.map('map', { center: [40.7128, -74.0060] });
map.show();
</script>

Creating the Map object​

G.map(selector: string|HTMLElement, options?: MapOptions): Map

There are a few ways to setup the Map object.

Only set the selector.

G.map(selector: string|HTMLElement)

ParameterTypeRequiredDescription
selectorA string or an HTML elementYesThe HTMLElement to display the map in, or any valid selector for document.querySelector.

In this case you should either use setOptions, one of the other set... methods to set the configuration.

const map = G.map('#mapSelector');
map.setOptions({ center: [40.7128, -74.0060] });

Pass the selector and the map options.

G.map(selector: string|HTMLElement, options: MapOptions)

ParameterTypeRequiredDescription
selectorA string or an HTML elementYesThe HTMLElement to display the map in, or any valid selector for document.querySelector.
optionsMapOptionsYesThe configuration options.
const map = G.map('.myMapSelector', {apiKey: 'my-api-key', libraries: 'places'});

Map selector​

The map selector parameter can be one of the following two values:

  • The HTML element to display the map in.
  • A string CSS selector for the HTML element to display the map in. Any valid selector for document.querySelector can be used.

The HTML element to display the map in.

<div class="myMap" style="aspect-ratio: 3/2"></div>

<script>
const mapEl = document.querySelector('.myMap');
const map = G.map(mapEl);
</script>

The id selector for the HTML element to display the map in.

<div id="map" style="aspect-ratio: 3/2"></div>

<script>
const map = G.map('#map');
</script>

The class selector for the HTML element to display the map in.

<div class="mapElement" style="aspect-ratio: 3/2"></div>

<script>
const map = G.map('.mapElement');
</script>

Map options​

Type MapOptions.

MapOptions is an object containing the configuration options for the Map object.

OptionTypeDefaultDescription
apiKeystringThe Google Maps API key. Only pass this if you're not using G.loader.
backgroundColorstringThe background color of the map. This can be any valid CSS color value. The color will be visible when the tiiles have not yet loaded as the user pans. This option can only be set when the map is initialized. Details
centerLatLngValue[0, 0]The center point for the map.
clickableIconsbooleantrueWhether the map icons are clickable or not. Details
colorSchemestringThe initial Map color scheme. This option can only be set when the map is initialized. Details
controlSizenumberThe size in pixels of the controls on the map that are made by the Maps JavaScript API. This does not apply to custom controls. This can only be set when the map is initialized. Details
disableDefaultUIbooleanfalseWhether to disable the default UI. Details
draggableCursorstringThe name or url of the cursor to display when mousing over a draggable map. Details
draggingCursorstringThe name or url of the cursor to display when the map is being dragged. Details
fullscreenControlboolean | FullscreenControltrueWhether to display the Fullscreen control on the map, or the FullscreenControl object to configure the Fullscreen control.
gestureHandlingstringThis controls how the API handles gestures on the map. Details
headingnumberSets the heading for aerial imagery in degrees measured clockwise from cardinal direction North. Details
headingInteractionEnabledbooleanfalseWhether the map should allow user control of the camera heading (rotation). Details
hideBusinessesbooleanfalseWhether to hide businesses, like stores, restaurants, and hotels. This hides the poi.business feature type. Has no effect if mapId is set. See hideBusinesses.
hidePointsOfInterestbooleanfalseWhether to hide all points of interest, like businesses, parks, schools, and attractions. This hides the poi feature type. Has no effect if mapId is set. See hidePointsOfInterest.
hideTransitbooleanfalseWhether to hide transit lines and stations, like bus stops, train stations, and rail lines. This hides the transit feature type. Has no effect if mapId is set. See hideTransit.
isFractionalZoomEnabledbooleanWhether the map should allow fractional zoom levels. Details
keyboardShortcutsbooleantrueWhether to allow the map to be controlled by the keyboard. Details
latnumber | stringThe latitude for the map center point. This is an alternate option to center and latitude. If you set this then you must also set lng or longitude.
latitudenumber | stringThe latitude for the map center point. This is an alternate option to center and lat. If you set this then you must also set lng or longitude.
librariesArray | stringAn array of Google Maps libraries to load. You can also pass a single string value for one library. Only pass this if you're not using G.loader.
lngnumber | stringThe longitude for the map center point. This is an alternate option to center and longitude. If you set this then you must also set lat or latitude.
longitudenumber | stringThe longitude for the map center point. This is an alternate option to center and lng. If you set this then you must also set lat or latitude.
mapIdstringThe Google Maps map id.
mapTypeControlboolean | MapTypeControltrueWhether to display the Map Type control on the map, or the MapTypeControl object to configure the Map Type control.
mapTypeIdstring | MapTypeIdMapTypeId.ROADMAPThe map type id to use for the map.
maxFitBoundsZoomnumber | nullThe maximum zoom level to use when fitting the map to a set of bounds.
maxZoomnumber | nullThe maximum zoom level for the map.
minFitBoundsZoomnumber | nullThe minimum zoom level to use when fitting the map to a set of bounds.
minZoomnumber | nullThe minimum zoom level for the map.
noClearbooleanfalseWhether to clear the contents of the map div. If true, then the map div contents will not be cleared. Details
renderingTypeG.RenderingTypeG.RenderingType.RASTERThe rendering type for the map. This sets if it should be a raster or vector map.
restrictionMapRestrictionValueThe boundry to restrict the map to. When set the user can only pan and zoom within this latitude/longitude bounds.
rotateControlboolean | RotateControltrueWhether to display the Rotate control on the map, or the RotateControl object to configure the Rotate control.
scaleControlboolean | ScaleControltrueWhether to display the Scale control on the map, or the ScaleControl object to configure the Scale control.
scrollwheelbooleantrueWhether to enable or disable zooming with the mouse scroll wheel. Details
streetViewStreetViewPanoramaA StreetViewPanorama to display when the Street View pegman is dropped on the map. Details
streetViewControlboolean | StreetViewControltrueWhether to display the Street View control on the map, or the StreetViewControl object to configure the Street View control.
stylesMapStyle | MapStyleValue[]The styles to apply to the map types. This allows you to style elements like roads or points of interest. Pass a single MapStyle object or an array of style rules. Ignored by Google if mapId is set. See the Style the map guide.
tiltnumberFor vector maps, this sets the angle of incidence of the map. Details
tiltInteractionEnabledbooleanWhether the map should allow user control of the camera tilt. Details
versionstringweeklyThe version of the Google Maps library to load. Only pass this if you're not using G.loader.
zoomnumber | string6The initial zoom level for the map.
zoomControlboolean | ZoomControltrueWhether to display the Zoom control on the map, or the ZoomControl object to configure the Zoom control.

Locate options​

Type LocateOptions.

These are the options for the locate method.

OptionTypeDefaultDescription
enableHighAccuracybooleanfalseIndicates if the application would like to receive the best possible results. If true and if the device is able to provide a more accurate position, it will do so. This can result in slower response times or increased power consumption on a mobile device. If false then the device can save resources by responding more quickly.
maximumAgenumber0The maximum age in milliseconds of a possible cached position that is acceptable to return. If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position. If set to Infinity the device must return a cached position regardless of its age.
timeoutnumberInfinityThe maximum time in milliseconds the device is allowed to take in order to return a position.
watchbooleantrueWhether to use watchPosition to track the user's location. If set to false, the user's location will only be retrieved once.

Locate position data​

Type LocationPosition.

This is the object data returned from the Geolocation API and sent to the 'locationfound' event. It's also passed to the onSuccess callback for locate. That callback has the type LocationOnSuccess, which is (position: LocationPosition) => void.

The values come from GeolocationPosition and GeolocationCoordinates.

The only guaranteed values are latitude, longitude, latLng, and timestamp. Test for other values before using them.

ValueTypeDescription
accuracynumberThe accuracy of the latitude and longitude values, expressed in meters.
altitudenumberThe position's altitude in meters.
altitudeAccuracynumberThe accuracy of the altitude expressed in meters.
headingnumberThe direction in which the device is facing.
latitudenumberThe user's latitude.
latLngLatLngA LatLng value holding the user's latitude and longitude.
longitudenumberThe user's longitude.
speednumberThe velocity that the device is moving, expressed in meters per second.
timestampnumberThe timestamp in milliseconds representing when the location was retrieved.

MapType type​

Type MapType.

A TypeScript type for the basic Google map types. It's one of 'hybrid', 'roadmap', 'satellite', or 'terrain'. It's based on google.maps.MapTypeId. Use the MapTypeId constants for the mapTypeId option.

Events​

All of the Google Map events can used. Below are the map events specific to this library.

You can use the plain text name for the event, or you can use the event constant.

EventDescription
locationerrorThere was an error getting the user's location. The event includes the error code and message from the GeolocationPositionError.
locationfoundThe user's location has been found. The event includes the location position data.
readyThe map is loaded, visible, and ready for use.

Properties​

PropertyTypeDescription
centerLatLngThe latitude and longitude center of the map. When setting, any LatLngValue can be used.
dataDataLayerThe map's own data layer. Read only.
disableDefaultUIbooleanWhether to disable the default UI. Details
fullscreenControlboolean | FullscreenControlWhether to display the Fullscreen control on the map, or the FullscreenControl object to configure the Fullscreen control.
hideBusinessesbooleanWhether businesses are hidden on the map.
hidePointsOfInterestbooleanWhether all points of interest are hidden on the map.
hideTransitbooleanWhether transit lines and stations are hidden on the map.
latitudenumberThe latitude value for the center point. When setting, the value can be a number or a string.
longitudenumberThe longitude value for the center point. When setting, the value can be a number or a string.
mapTypeControlboolean | MapTypeControlWhether to display the Map Type control on the map, or the MapTypeControl object to configure the Map Type control.
mapTypeIdstring | MapTypeIdThe map type id to use for the map.
maxFitBoundsZoomnumber | nullThe maximum zoom level to use when fitting the map to a set of bounds.
maxZoomnumber | nullThe maximum zoom level for the map.
minFitBoundsZoomnumber | nullThe minimum zoom level to use when fitting the map to a set of bounds.
minZoomnumber | nullThe minimum zoom level for the map.
restrictionMapRestriction | undefinedThe boundry to restrict the map to. When set the user can only pan and zoom within this latitude/longitude bounds. When setting, any MapRestrictionValue can be used.
rotateControlboolean | RotateControlWhether to display the Rotate control on the map, or the RotateControl object to configure the Rotate control.
scaleControlboolean | ScaleControlWhether to display the Scale control on the map, or the ScaleControl object to configure the Scale control.
streetViewControlboolean | StreetViewControlWhether to display the Street View control on the map, or the StreetViewControl object to configure the Street View control.
zoomnumberThe zoom level of the map. When setting, the value can be a number or a string.
zoomControlboolean | ZoomControlWhether to display the Zoom control on the map, or the ZoomControl object to configure the Zoom control.

center​

Get and set the center point of the map. The value returned is the same as getCenter;

// Get the center point. A LatLng value is returned.
const center = map.center;
// Set the center point as a lat/lng object
map.center = {lat: 48.86, lng: 2.35}
// Set the center point as a LatLng object
map.center = G.latLng(48.86, 2.35);

data​

Get the map's own data layer. Every map has one.

The layer is created the first time that you use this and you get the same object back every time after that.

map.data.setStyle({ fillColor: '#4caf50' });
map.data.addPolygon(path);

Because Google gives each map one shared data layer, everything that uses map.data puts its features in the same place. See The map's data layer is shared for when that matters and how to use a layer of your own instead.

disableDefaultUI​

Get and set whether to disable the default UI. Details.

// Get whether the default UI is disabled
const isDisabled = map.disableDefaultUI;
// Disable the default UI
map.disableDefaultUI = true;

// Enable the default UI
map.disableDefaultUI = false;

fullscreenControl​

Get the FullscreenControl configuration, or set whether to display the Fullscreen control on the map, or set the FullscreenControl configuration.

// Get the current FullscreenControl configuration
const control = map.fullscreenControl;
// Disable the fullscreen control
map.fullscreenControl = false;
// Set the fullscreen control configuration with a FullscreenControl object
map.fullscreenControl = G.fullscreenControl({
position: G.ControlPosition.LEFT_CENTER,
});

hideBusinesses​

Get and set whether businesses are hidden on the map. This hides the poi.business feature type, which includes things like stores, restaurants, and hotels. Other points of interest, like parks and schools, are still shown.

This can be set before or after the map has been displayed. If the map is already displayed then it's updated right away.

// Get whether businesses are hidden
const hidden = map.hideBusinesses;
// Hide businesses
map.hideBusinesses = true;

// Show businesses again
map.hideBusinesses = false;
note

This works by adding a map style, so it has no effect when the map has a mapId. See the Style the map guide.

hidePointsOfInterest​

Get and set whether all points of interest are hidden on the map. This hides the poi feature type, which includes businesses, parks, schools, attractions, and places of worship.

Because businesses are a type of point of interest, they stay hidden while this is true, even if hideBusinesses is false.

This can be set before or after the map has been displayed. If the map is already displayed then it's updated right away.

// Get whether points of interest are hidden
const hidden = map.hidePointsOfInterest;
// Hide all points of interest
map.hidePointsOfInterest = true;

// Show points of interest again
map.hidePointsOfInterest = false;
note

This works by adding a map style, so it has no effect when the map has a mapId. See the Style the map guide.

hideTransit​

Get and set whether transit lines and stations are hidden on the map. This hides the transit feature type, which includes things like bus stops, train stations, and rail lines.

This can be set before or after the map has been displayed. If the map is already displayed then it's updated right away.

// Get whether transit is hidden
const hidden = map.hideTransit;
// Hide transit lines and stations
map.hideTransit = true;

// Show transit again
map.hideTransit = false;
note

This works by adding a map style, so it has no effect when the map has a mapId. See the Style the map guide.

latitude​

Get and set the latitude part of the center point. This allows you to update the center point when you only need to update the latitude value.

// A number is returned
const latitude = map.latitude;
// When setting, the value can be a number or a string
map.latitude = 48.86;
map.latitude = '48.86';

longitude​

Get and set the longitude part of the center point. This allows you to update the center point when you only need to update the longitude value.

// A number is returned
const longitude = map.longitude;
// When setting, the value can be a number or a string
map.longitude = 2.35;
map.longitude = '2.35';

mapTypeControl​

Get the MapTypeControl configuration, or set whether to display the Map Type control on the map, or set the MapTypeControl configuration.

// Get the MapTypeControl object
const control = map.mapTypeControl;
// Disable the map type control
map.mapTypeControl = false;
// Set the map type control configuration with a MapTypeControl object
map.mapTypeControl = G.mapTypeControl({
mapTypeIds: [G.MapTypeId.ROADMAP, G.MapTypeId.TERRAIN],
position: G.ControlPosition.LEFT_CENTER,
style: G.MapTypeControlStyle.DROPDOWN_MENU,
});

maxFitBoundsZoom​

Get and set the maximum zoom level when fitting the map to a set of bounds. This allows you to not have to pass a maximum zoom value to the fitBounds method. If it's not set, or set to null then maxZoom will be used when fitting to bounds. If both maxFitBoundsZoom and maxZoom are not set then you will want to pass a maximum zoom value to fitBounds. Valid zoom values are numbers from zero up to the supported maximum zoom level.

info

Zoom levels go from 0, the most zoomed out, to 22, the most zoomed in.

A higher zoom number means that the map will be more zoomed in.

A lower zoom number means that the map will be more zoomed out.

const maxFitBoundsZoom = map.maxFitBoundsZoom;
map.maxFitBoundsZoom = 12;

maxZoom​

Get and set the maximum zoom level on the map. If it's set to null then the maximum zoom from the current map type is used instead. Valid zoom values are numbers from zero up to the supported maximum zoom level.

info

Zoom levels go from 0, the most zoomed out, to 22, the most zoomed in.

A higher zoom number means that the map will be more zoomed in.

A lower zoom number means that the map will be more zoomed out.

const maxZoom = map.maxZoom;
map.maxZoom = 12;

minFitBoundsZoom​

Get and set the minimum zoom level when fitting the map to a set of bounds. This allows you to not have to pass a minimum zoom value to the fitBounds method. If it's not set, or set to null then minZoom will be used when fitting to bounds. If both minFitBoundsZoom and minZoom are not set then you may want to pass a minimum zoom value to fitBounds. Valid zoom values are numbers from zero up to the supported maximum zoom level.

info

Zoom levels go from 0, the most zoomed out, to 22, the most zoomed in.

A higher zoom number means that the map will be more zoomed in.

A lower zoom number means that the map will be more zoomed out.

const minFitBoundsZoom = map.minFitBoundsZoom;
map.minFitBoundsZoom = 12;

minZoom​

Get and set the minimum zoom level on the map. If it's set to null then the minimum zoom from the current map type is used instead. Valid zoom values are numbers from zero up to the supported maximum zoom level.

info

Zoom levels go from 0, the most zoomed out, to 22, the most zoomed in.

A higher zoom number means that the map will be more zoomed in.

A lower zoom number means that the map will be more zoomed out.

const minZoom = map.minZoom;
map.minZoom = 12;

restriction​

Get and set the bounds restriction on the map.

Get the bounds restriction value. If the restriction value has been set then a MapRestriction object will be returned.

// Get the MapRestriction restriction object if it's set
const restriction = map.restriction;

Set the bounds restriction value.

map.restriction = G.mapRestriction({
latLngBounds: [
[40.712, -74.227],
[40.774, -74.125]
],
strictBounds: true
});

rotateControl​

Get the RotateControl configuration, or set whether to display the Rotate control on the map, or set the RotateControl configuration.

// Get the current RotateControl configuration
const control = map.rotateControl;
// Disable the rotate control
map.rotateControl = false;
// Set the rotate control configuration with a RotateControl object
map.rotateControl = G.rotateControl({
position: G.ControlPosition.LEFT_CENTER,
});

scaleControl​

Get the ScaleControl configuration, or set whether to display the Scale control on the map, or set the ScaleControl configuration.

// Get the current ScaleControl configuration
const control = map.scaleControl;
// Enable the scale control
map.scaleControl = true;
// Set the scale control configuration with a ScaleControl object
map.scaleControl = G.scaleControl({
enabled: true
});

streetViewControl​

Get the StreetViewControl configuration, or set whether to display the Street View control on the map, or set the StreetViewControl configuration.

// Get the current StreetViewControl configuration
const control = map.streetViewControl;
// Enable the street view control
map.streetViewControl = true;
// Set the street view control configuration with a StreetViewControl object
map.streetViewControl = G.streetViewControl({
enabled: true,
position: G.ControlPosition.LEFT_CENTER
});

zoom​

Get and set the zoom level on the map.

info

Zoom levels go from 0, the most zoomed out, to 22, the most zoomed in.

const zoom = map.zoom;
// When setting, the value can be a number or a string
map.zoom = 11;
map.zoom = '11';

zoomControl​

Get the ZoomControl configuration, or set whether to display the Zoom control on the map, or set the ZoomControl configuration.

// Get the current ZoomControl configuration
const control = map.zoomControl;
// Disable the zoom control
map.zoomControl = false;
// Set the zoom control configuration with a ZoomControl object
map.zoomControl = G.zoomControl({
position: G.ControlPosition.LEFT_CENTER,
});

Methods​

  • Methods inherited from Evented.
  • Methods inherited from Base

addCustomControl​

addCustomControl(position: ControlPositionValue, element: HTMLElement): Map

Add a custom control to the map. Custom controls are often buttons that do something when clicked. For example, you could have a button that toggles the display of something on the map.

The custom control is positioned on the map with the ControlPosition values.

ParameterTypeRequiredDescription
positionControlPositionYesThe position on the map to display the control.
elementHTMLElementYesThe HTML element for the custom control. This is often a div or button.
const customBtn = document.createElement('button');
customBtn.textContent = 'Custom Control';
customBtn.className = 'myCustomBtn';
customBtn.addEventListener('click', () => {
console.log('Custom Control clicked');
});
map.addCustomControl(G.ControlPosition.BLOCK_START_INLINE_CENTER, customBtn);

addGeoJson​

addGeoJson(geoJson: object, options?: LoadOptions): Promise<DataFeature[]>

Add a GeoJson object to the map's data layer. This is a shortcut for map.data.addGeoJson().

Resolves with the DataFeature objects that were added.

ParameterTypeRequiredDescription
geoJsonobjectYesThe GeoJson object to add.
optionsLoadOptionsThe options for adding the data.
const features = await map.addGeoJson(geoJson);

addToBounds​

addToBounds(value: LatLngValue | LatLngValue[]): Map

Adds a latitude/longitude value to the internal map bounds object. This is an alternate way to set up map bounds instead of using a separate LatLngBounds object.

Once you've added at least one value to the bounds you can call the fitBounds method with no parameter. That will tell the map object to use the internal bounds value.

This does the same as the extend method in the LatLngBounds object except that it does it on an internal LatLngBounds object in the map object.

ParameterTypeRequiredDescription
latLngValueLatLngValue or array of LatLngValue valuesYesThe latitude and longitude value(s).
map.addToBounds([40.712, -74.227]);

You can pass the LatLngValue in a few ways.

Pass a single LatLng value:

map.addToBounds(latLngObject);
map.addToBounds([40.712, -74.227]);
map.addToBounds({lat: 40.712, lng: -74.227});
map.addToBounds({latitude: 40.712, longitude: -74.227});

Pass an array of LatLng values:

map.addToBounds([
latLngObject,
latLngObject2
]);
map.addToBounds([
[40.712, -74.227],
[40.774, -74.125]
]);
map.addToBounds([
{lat: 40.712, lng: -74.227},
{lat: 40.774, lng: -74.125}
]);
map.addToBounds([
{latitude: 40.712, longitude: -74.227},
{latitude: 40.774, longitude: -74.125}
]);

attachInfoWindow​

attachInfoWindow(infoWindowValue: InfoWindowValue, event?: string): InfoWindow

Attach an InfoWindow to the map. This makes it easy to have an InfoWindow show when the map is clicked.

ParameterTypeDefaultRequiredDescription
infoWindowValueInfoWindowValueYesThe InfoWindow, InfoWindow options, or content for the InfoWindow
eventstring'click'The event to trigger displaying the InfoWindow.

Allowed event values include:

  • click - Toggle the display of the InfoWindow when clicking on the map.
  • clickon - Show the InfoWindow when clicking on the map. It will always be shown and can't be hidden once the map is clicked. This may be useful if you want to show a popup each time you click on the map.
  • hover - Show the InfoWindow when hovering over the map. Hide the InfoWindow when the map is no longer hovered.
map.attachInfoWindow('My content for the info window');

attachPopup​

attachPopup(popupValue: AttachPopupValue, event?: string): Popup

Attach a popup to the map. This makes it easy to have a popup show when the map is clicked.

ParameterTypeDefaultRequiredDescription
popupValuePopupValue or PopupCallbackYesThe Popup, Popup options, or content for the Popup, or a function that returns one of those.
eventstring'click'The event to trigger displaying the popup.

Allowed event values include:

  • click - Toggle the display of the popup when clicking on the map.
  • clickon - Show the popup when clicking on the map. It will always be shown and can't be hidden once the map is clicked. This may be useful if you want to show a popup each time you click on the map.
  • hover - Show the popup when hovering over the map. Hide the popup when the map is no longer hovered.
map.attachPopup('My content for the popup', 'clickon');

Pass a function to work out the popup when it's shown rather than up front. It's called with the map and can return the content, a PopupOptions object, or a Popup object to show instead. See PopupCallback.

map.attachPopup((map) => `The zoom level is ${map.getZoom()}`, 'clickon');

attachTooltip​

attachTooltip(tooltipValue: AttachTooltipValue, event?: string): Tooltip

Attach a Tooltip to the map. This makes it easy to show a tooltip when the map is hovered or clicked.

ParameterTypeDefaultRequiredDescription
tooltipValueTooltipValue or TooltipCallbackYesThe tooltip value, or a function that returns one.
eventstring'hover'The event to trigger the tooltip.

Allowed event values include:

  • click - Toggle the display of the tooltip when clicking on the map.
  • clickon - Show the tooltip when clicking on the map. It will always be shown and can't be hidden once the map is clicked. This may be useful if you want to show a tooltip each time you click on the map.
  • hover - Show the tooltip when hovering over the map. Hide the tooltip when the map is no longer hovered.

This is an alternate way to set a tooltip on a map compared to the Tooltip attachTo() method.

map.attachTooltip({
className: 'MapTooltip',
content: 'Map tooltip here'
});
map.attachTooltip({
className: 'MapTooltip',
content: 'Shown when map is clicked'
}, 'clickon');

Pass a function to work out the tooltip when it's shown rather than up front. It's called with the map. See TooltipCallback.

map.attachTooltip((map) => `The zoom level is ${map.getZoom()}`);

clearBounds​

clearBounds(): Map

Clear the existing bounds. Internally this just replaces the internal bounds object with a new one. It does not change anything on the Google Maps object.

map.clearBounds();

display​

display(callback?: () => void): Promise<Map>

Display the map. Alias to show().

ParameterTypeRequiredDescription
callbackFunctionA function to call after the map is displayed.
map.display();

doDisableDefaultUI​

doDisableDefaultUI(): Map

Disable the default UI.

map.doDisableDefaultUI();

enableDefaultUI​

enableDefaultUI(): Map

Enable the default UI.

map.enableDefaultUI();

fitBounds​

fitBounds(bounds?: LatLngBoundsValue, maxZoom?: number, minZoom?: number): Promise<Map>

Sets the viewport to contain the given bounds.

ParameterTypeRequiredDescription
boundsLatLngBoundsValueThe bounds to fit the map to.
maxZoomnumberThe maximum zoom level to zoom to when fitting the bounds. Higher numbers will zoom in more.
minZoomnumberThe minimum zoom level to zoom to when fitting the bounds. Lower numbers will zoom out more.
tip

If you are having an issue where the map tiles aren't loading after calling fitBounds() then try these options:

Call fitBounds() after the map has been displayed.

map.show(() => {
map.fitBounds();
});

Add a brief timeout with setTimeout before calling fitBounds.

map.show(() => {
setTimeout(() => {
map.fitBounds();
}, 100);
});

If the bounds value is not set then the internal map bounds data will be used. The internal map bounds data is setup with addToBounds.

The bounds parameter can be:

A LatLngBounds object.

map.fitBounds(latLngBoundsObject);

An array of LatLngValue values.

map.fitBounds([
[51.5074, -0.1278],
[50.024, -1.324]
]);
map.fitBounds([
{lat: 51.5074, lng: -0.1278},
{lat: 50.024, lng: -1.324}
]);
map.fitBounds([
latLngObject1,
latLngObject2
]);

A LatLngValue value.

This isn't that useful because it only sets one point. But, it's supported.

map.fitBounds([51.5074, -0.1278]);
map.fitBounds({lat: 51.5074, lng: -0.1278});
map.fitBounds(latLngObject);

You can also set the maximum zoom level.

map.fitBounds(latLngObject, 16);

No value.

If you set up one or more latitude/longitude values with addToBounds then you can call fitBounds() with no parameter. This will tell the map object to use the internal bounds value.

map.addToBounds([40.712, -74.227]);
map.addToBounds([41.324, -74.952]);
map.fitBounds();
// Or set the maxiumum zoom level
map.fitBounds(null, 15);

fitToBounds​

fitToBounds(bounds?: LatLngBoundsValue, maxZoom?: number, minZoom?: number): Promise<Map>

Sets the viewport to contain the given bounds. Alias to fitBounds.

ParameterTypeRequiredDescription
boundsLatLngBoundsValueThe bounds to fit the map to.
maxZoomnumberThe maximum zoom level to zoom to when fitting the bounds. Higher numbers will zoom in more.
minZoomnumberThe minimum zoom level to zoom to when fitting the bounds. Lower numbers will zoom out more.

See fitBounds for examples and more information

getBounds​

getBounds(): Promise<LatLngBounds | undefined>

Get the bounds for the map viewport. If the map hasn't been set up yet then undefined is returned.

map.getBounds().then((bounds) => {
// Do something with the bounds
});

getCenter​

getCenter(): LatLng

Returns the current center point for the map.

const center = map.getCenter();

getDiv​

getDiv(): HTMLElement | undefined

Returns the map container div. If the map hasn't been set up yet then undefined is returned.

const div = map.getDiv();

getIsReady​

getIsReady(): boolean

Gets whether the map is ready and visible. This also means that the map library is loaded.

if (map.getIsReady()) {
// Do something
}

getProjection​

getProjection(): google.maps.Projection | undefined

Returns the Google Maps Projection object for the map.

If the map hasn't been set up yet then undefined is returned.

const projection = map.getProjection();

getZoom​

getZoom(): number

Get the current zoom level for the map.

const zoom = map.getZoom();

You can get the same value from the zoom property.

const zoom = map.zoom;

load​

load(callback?: () => void): Promise<Map>

Loads the Google Maps API library and displays the map.

The ready event is triggered after the map is loaded and displayed. This also triggers the map_load Loader event.

This is different from the show() method because this will load the map and show the map. The show() method will only show the map and depends on G.loader to load the map.

ParameterTypeRequiredDescription
callbackFunctionA function to call after the map is loaded and displayed.

load usage​

Just load and show the map:

map.load();

Use the Promise:

map.load().then(() => {
// Do something
});

Await the promise:

async loadAndDisplayTheMap() {
await map.load();
// Do something next
}

Use the callback:

map.load(() => {
// Do something
});

While it's an odd choice, you can do both the callback and handle the promise. They will be executed at the same time.

map.load(() => {
// Do something
}).then(() => {
// Also do something
});

loadGeoJson​

loadGeoJson(url: string | string[], options?: LoadOptions): Promise<DataFeature[]>

Load GeoJson data into the map's data layer from a url. This is a shortcut for map.data.loadGeoJson().

More than one url can be passed. The promise then resolves once every file has loaded, with all of the DataFeature objects from all of the files.

ParameterTypeRequiredDescription
urlstring | string[]YesThe url to load the GeoJson from, or an array of urls.
optionsLoadOptionsThe options for loading the data.
const features = await map.loadGeoJson('/parcels.json');

Fit the map to the data once it's loaded.

map.loadGeoJson('/parcels.json', { fitBounds: true });

locate​

locate(options?: LocateOptions | (position: LocationPosition) => void, onSuccess?: (position: LocationPosition) => void): Map

Try to locate the user using the GeoLocation API.

ParameterTypeRequiredDescription
optionsLocateOptions or functionThe locate options or a callback function for when the location is found.
onSuccessfunctionThe callback function for when the location is found. Only pass this if options is passed as the options object.

There are a few ways to handle when the user's location is found:

Pass a callback function to the locate() function.

map.locate({watch: false}, (position) => {
// Do something with the position
});
map.locate((position) => {
// Do something with the position
});

Listen for the 'locationfound' event.

map.on('locationfound', (position) => {
// Do something with the position
});

// or

map.on(G.MapEvents.LOCATION_FOUND, (position) => {
// Do something with the position
});

// or

map.onLocationFound((position) => {
// Do something with the position
});

onBoundsChanged​

onBoundsChanged(callback: EventCallback): void

Callback for when the viewport bounds have changed.

This is a convenience function for map.on(G.MapEvents.BOUNDS_CHANGED, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onBoundsChanged(() => {
// Do something
})

onCenterChanged​

onCenterChanged(callback: EventCallback): void

Callback for when the map center property changes.

This is a convenience function for map.on(G.MapEvents.CENTER_CHANGED, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onCenterChanged(() => {
// Do something
})

onClick​

onClick(callback: EventCallback): void

Callback for when the map is clicked.

This is a convenience function for map.on(G.MapEvents.CLICK, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onClick(() => {
// Do something
})

onContextMenu​

onContextMenu(callback: EventCallback): void

Callback for when the DOM contextmenu is fired on the map container.

This is a convenience function for map.on(G.MapEvents.CONTEXT_MENU, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onContextMenu(() => {
// Do something
})

onDblClick​

onDblClick(callback: EventCallback): void

Callback for when the map is double clicked.

This is a convenience function for map.on(G.MapEvents.DBLCLICK, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onDblClick(() => {
// Do something
})

onDrag​

onDrag(callback: EventCallback): void

Callback for when the user drags the map.

This is a convenience function for map.on(G.MapEvents.DRAG, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onDrag(() => {
// Do something
})

onDragEnd​

onDragEnd(callback: EventCallback): void

Callback for when the user stops dragging the map.

This is a convenience function for map.on(G.MapEvents.DRAG_END, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onDragEnd(() => {
// Do something
})

onDragStart​

onDragStart(callback: EventCallback): void

Callback for when the user starts dragging the map.

This is a convenience function for map.on(G.MapEvents.DRAG_START, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onDragStart(() => {
// Do something
})

onHeadingChanged​

onHeadingChanged(callback: EventCallback): void

Callback for when the map heading value changes.

This is a convenience function for map.on(G.MapEvents.HEADING_CHANGED, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onHeadingChanged(() => {
// Do something
})

onIdle​

onIdle(callback: EventCallback): void

Callback for when the map becomes idle after panning or zooming.

This is a convenience function for map.on(G.MapEvents.IDLE, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onIdle(() => {
// Do something
})

onIsFractionalZoomEnabledChanged​

onIsFractionalZoomEnabledChanged(callback: EventCallback): void

Callback for when the isFractionalZoomEnabled property has changed.

This is a convenience function for map.on(G.MapEvents.IS_FRACTIONAL_ZOOM_ENABLED_CHANGED, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onIsFractionalZoomEnabledChanged(() => {
// Do something
})

onLocationError​

onLocationError(callback: EventCallback): void

Callback for when there is an error getting the user's location.

This is a convenience function for map.on(G.MapEvents.LOCATION_ERROR, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onLocationError(() => {
// Do something
})

onLocationFound​

onLocationFound(callback: EventCallback): void

Callback for when the user's location has been found.

This is a convenience function for map.on(G.MapEvents.LOCATION_FOUND, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onLocationFound(() => {
// Do something
})

onMapCapabilitiesChanged​

onMapCapabilitiesChanged(callback: EventCallback): void

Callback for when the map capabilities change.

This is a convenience function for map.on(G.MapEvents.MAP_CAPABILITIES_CHANGED, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onMapCapabilitiesChanged(() => {
// Do something
})

onMapTypeIdChanged​

onMapTypeIdChanged(callback: EventCallback): void

Callback for when the mapTypeId property changes.

This is a convenience function for map.on(G.MapEvents.MAP_TYPE_ID_CHANGED, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onMapTypeIdChanged(() => {
// Do something
})

onMouseMove​

onMouseMove(callback: EventCallback): void

Callback for when the user's mouse moves over the map container.

This is a convenience function for map.on(G.MapEvents.MOUSE_MOVE, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onMouseMove(() => {
// Do something
})

onMouseOut​

onMouseOut(callback: EventCallback): void

Callback for when the user's mouse exits the map container.

This is a convenience function for map.on(G.MapEvents.MOUSE_OUT, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onMouseOut(() => {
// Do something
})

onMouseOver​

onMouseOver(callback: EventCallback): void

Callback for when the user's mouse enters the map container.

This is a convenience function for map.on(G.MapEvents.MOUSE_OVER, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onMouseOver(() => {
// Do something
})

onProjectionChanged​

onProjectionChanged(callback: EventCallback): void

Callback for when the map projection has changed.

This is a convenience function for map.on(G.MapEvents.PROJECTION_CHANGED, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onProjectionChanged(() => {
// Do something
})

onReady​

onReady(callback: EventCallback): void

Callback for when the map is ready and visible.

This is a convenience function for map.onceImmediate(G.MapEvents.READY, callback). The callback is only called once. If the map is already ready then the callback is called right away.

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onReady(() => {
// Do something
})

onRenderingTypeChanged​

onRenderingTypeChanged(callback: EventCallback): void

Callback for when the map renderingType has changed.

This is a convenience function for map.on(G.MapEvents.RENDERING_TYPE_CHANGED, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onRenderingTypeChanged(() => {
// Do something
})

onTilesLoaded​

onTilesLoaded(callback: EventCallback): void

Callback for when the visible tiles have finished loading.

This is a convenience function for map.on(G.MapEvents.TILES_LOADED, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onTilesLoaded(() => {
// Do something
})

onTiltChanged​

onTiltChanged(callback: EventCallback): void

Callback for when the map tilt property changes.

This is a convenience function for map.on(G.MapEvents.TILT_CHANGED, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onTiltChanged(() => {
// Do something
})

onZoomChanged​

onZoomChanged(callback: EventCallback): void

Callback for when the map zoom property changes.

This is a convenience function for map.on(G.MapEvents.ZOOM_CHANGED, callback).

ParameterTypeRequiredDescription
callbackFunctionYesThe callback function that will be called when the event is dispatched.
map.onZoomChanged(() => {
// Do something
})

panBy​

panBy(x: number, y: number): void

Changes the center of the map by the given distance in pixels.

ParameterTypeRequiredDescription
xnumberYesThe number of pixels to move the map in the x direction.
ynumberYesThe number of pixels to move the map in the y direction.
map.panBy(100, 32);

panTo​

panTo(value: LatLngValue): void

Changes the center of the map to the lat/lng value. If the change is less than both the width and height of the map, the transition will be smoothly animated.

ParameterTypeRequiredDescription
valueLatLngValueYesThe latitude/longitude value to pan to.
map.panTo([34.0522, -118.2437]);

resize​

resize(element?: HTMLElement | string): void

Resize the the map container to force the map to redraw itself. This is useful when the map is not displaying correctly, such as when the map is hidden and then shown.

This will resize the element that the map is rendered in by default. If you need to resize a different element, pass that element as the first argument.

The element will have it's height adjusted by 1 pixel and then 100ms later the height will be set back to it's original value. This will trigger the Google map to resize itself and it should fix any layout issues.

ParameterTypeRequiredDescription
elementHTMLElement | stringThe element to resize if you don't want to resize the map container. This can be an HTMLElement or a CSS selector.

Resize the map element.

map.resize();

Resize another element around the map. You may need to do this if another element around the map has a set height and the map container is set to be 100% height.

map.resize(mapWrapperElement);

Resize another element by passing a selector instead of an HTML element.

map.resize('#someSelector');
// or
map.resize('.someOtherSelector');

setApiKey​

setApiKey(key: string): Map

Set the Google Maps API key. You would only use this if you are not using the G.loader object to load the Google Maps API library.

ParameterTypeRequiredDescription
keystringYesThe API key.

An error is thrown if the key is not a string with a value.

map.setApiKey('my-api-key');

setCenter​

setCenter(latitude: number | LatLngValue, longitude?: number): Map

Set the center point for the map.

ParameterTypeRequiredDescription
latitudenumber or LatLngValueYesThe latitude value or the latitude/longitude value.
longitudenumberThe longitude value. Set this if latitude is a number.
map.setCenter(34.0522, -118.2437);
map.setCenter([34.0522, -118.2437]);
map.setCenter({lat: 34.0522, lng: -118.2437});
map.setCenter({latitude: 34.0522, longitude: -118.2437});
map.setCenter(latLngObject);

setHideBusinesses​

setHideBusinesses(value: boolean = true): Map

Set whether to hide businesses on the map. This is the same as setting the hideBusinesses property, but it returns the map so it can be chained.

This can be called before or after the map has been displayed.

ParameterTypeRequiredDefaultDescription
valuebooleantrueWhether to hide businesses.
// Hide businesses
map.setHideBusinesses();

// Show businesses again
map.setHideBusinesses(false);

setHidePointsOfInterest​

setHidePointsOfInterest(value: boolean = true): Map

Set whether to hide all points of interest on the map. This is the same as setting the hidePointsOfInterest property, but it returns the map so it can be chained.

This can be called before or after the map has been displayed.

ParameterTypeRequiredDefaultDescription
valuebooleantrueWhether to hide all points of interest.
// Hide all points of interest
map.setHidePointsOfInterest();

// Show points of interest again
map.setHidePointsOfInterest(false);

setHideTransit​

setHideTransit(value: boolean = true): Map

Set whether to hide transit lines and stations on the map. This is the same as setting the hideTransit property, but it returns the map so it can be chained.

This can be called before or after the map has been displayed.

ParameterTypeRequiredDefaultDescription
valuebooleantrueWhether to hide transit lines and stations.
// Hide transit and businesses
map.setHideTransit().setHideBusinesses();

// Show transit again
map.setHideTransit(false);

setLatitudeLongitude​

setLatitudeLongitude(latitude: number | string, longitude: number | string, updateCenter: boolean = true): Map

Set the latitude and longitude values and optionally update the center point.

This is an alternate method to setting the latitude and longitude values individually, or using setCenter().

You can choose to not update the center point with this method and only update the internal latitude and longitude values. If updateCenter is false then the map's center point is not changed.

The times when you would not want to update the center point are when you are setting the latitude and longitude and you don't want to recenter the map, but you want the latitude and longitude values to be available for future times when the map may be centered.

ParameterTypeRequiredDefaultDescription
latitudenumber | stringYesThe latitude value.
longitudenumber | stringYesThe longitude value.
updateCenterbooleantrueWhether to also update the map center point.
map.setLatitudeLongitude('34.0522', '-118.2437');

setMapTypeId​

setMapTypeId(mapTypeId: string): Map

Set the map type id to use for the map.

ParameterTypeRequiredDescription
mapTypeIdstring | MapTypeIdYesThe map type id to use for the map.
map.setMapTypeId(G.MapTypeId.TERRAIN);

setOptions​

setOptions(options: MapOptions): Map

Set the map options. You can use this to set the initial options for the map or to change the options after the map has loaded.

ParameterTypeRequiredDescription
optionsMapOptionsYesThe map options.
map.setOptions({
center: [34.0522, -118.2437],
zoom: 10
});

setZoom​

setZoom(zoom: number | string): Map

Set the zoom level for the map.

ParameterTypeRequiredDescription
zoomnumber | stringYesThe zoom level.
info

Zoom levels go from 0, the most zoomed out, to 22, the most zoomed in.

map.setZoom(10);

show​

show(callback?: () => void): Promise<Map>

Display the map.

The ready event is triggered after the map is loaded and displayed. This also triggers the map_load Loader event.

ParameterTypeRequiredDescription
callbackFunctionA function to call after the map is displayed.
warning

This method does not load the Google Maps API library. You must use G.loader to load the map.

The load() method will load and show the map. This will only show the map and depends on G.loader to load the map.

Display usage.

Just show the map:

G.loader().setApiKey(apiKey).load();
map.show();

Use the Promise:

G.loader().setApiKey(apiKey).load(() => {
map.show().then(() => {
// Do something
});
});

Await the promise:

async showTheMap() {
await map.show();
// Do something after loading
}

Use the callback:

map.show(() => {
// Do something
});

While it's an odd choice, you can do both the callback and handle the promise. They will be executed at the same time.

map.show(() => {
// Do something
}).then(() => {
// Also do something
});

stopLocate​

stopLocate(): Map

Stop watching for the user's location.

map.stopLocate();

toGoogle​

toGoogle(): google.maps.Map

Returns the Google Maps Map object.

const googleObject = map.toGoogle();