Класс карты
google.maps . Map
Класс google.maps . Map
Этот класс расширяет MVCObject
.
Получите доступ, вызвав const {Map} = await google.maps.importLibrary("maps")
. См. Библиотеки в Maps JavaScript API .
Конструктор | |
---|---|
Map | Map(mapDiv[, opts]) Параметры:
Создает новую карту внутри заданного HTML-контейнера, который обычно представляет собой элемент DIV . |
Характеристики | |
---|---|
controls | Тип: Array < MVCArray < HTMLElement >> Дополнительные элементы управления для прикрепления к карте. Чтобы добавить элемент управления на карту, добавьте <div> элемента управления в MVCArray , соответствующий ControlPosition , в котором он должен отображаться. |
data | Тип: Data Экземпляр Data , привязанный к карте. Добавьте объекты к этому объекту Data , чтобы удобно отображать их на этой карте. |
mapTypes | Тип: MapTypeRegistry Реестр экземпляров MapType по идентификатору строки. |
overlayMapTypes | Дополнительные типы карт для наложения. Типы наложенных карт будут отображаться поверх базовой карты, к которой они прикреплены, в том порядке, в котором они появляются в массиве overlayMapTypes (наложения с более высокими значениями индекса отображаются перед наложениями с более низкими значениями индекса). |
Методы | |
---|---|
fitBounds | fitBounds(bounds[, padding]) Параметры:
Возвращаемое значение: нет Устанавливает область просмотра, чтобы она содержала заданные границы. Примечание. Когда для карты установлено значение display: none , функция fitBounds считывает размер карты как 0x0 и, следовательно, ничего не делает. Чтобы изменить область просмотра, когда карта скрыта, установите для карты visibility: hidden , тем самым гарантируя, что div карты имеет реальный размер. Для векторных карт этот метод устанавливает нулевые значения наклона и направления карты по умолчанию. Вызов этого метода может вызвать плавную анимацию, поскольку карта перемещается и масштабируется, чтобы соответствовать границам. Будет ли этот метод анимировать, зависит от внутренней эвристики. |
getBounds | getBounds() Параметры: Нет Возвращаемое значение: LatLngBounds |undefined Границы широты/долготы текущего окна просмотра. Возвращает границы широты/долготы текущего окна просмотра. Если видно более одной копии мира, границы по долготе варьируются от -180 до 180 градусов включительно. Если карта еще не инициализирована или центр и масштаб не установлены, результат undefined . Для векторных карт с ненулевым наклоном или направлением возвращаемые границы широты/долготы представляют собой наименьшую ограничивающую рамку, включающую видимую область окна просмотра карты. См. MapCanvasProjection.getVisibleRegion для получения точной видимой области окна просмотра карты. |
getCenter | getCenter() Параметры: Нет Возвращаемое значение: LatLng |undefined |
getClickableIcons | getClickableIcons() Параметры: Нет Возвращаемое значение: boolean|undefined Возвращает кликабельность значков карты. Значок карты обозначает достопримечательность, также известную как POI. Если возвращаемое значение равно true , значки на карте можно щелкнуть. |
getDatasetFeatureLayer | getDatasetFeatureLayer(datasetId) Параметры:
Возвращаемое значение: FeatureLayer Возвращает FeatureLayer для указанного datasetId . Идентификаторы наборов данных должны быть настроены в Google Cloud Console. Если идентификатор набора данных не связан со стилем карты или стиль, управляемый данными, недоступен (нет идентификатора карты, нет векторных листов, векторных слоев стиля, управляемого данными, или наборов данных, настроенных в стиле карты), это регистрирует ошибка, и результирующий FeatureLayer.isAvailable будет ложным. |
getDiv | getDiv() Параметры: Нет Возвращаемое значение: HTMLElement Объект mapDiv карты. |
getFeatureLayer | getFeatureLayer(featureType) Параметры:
Возвращаемое значение: FeatureLayer Возвращает FeatureLayer определенного FeatureType . FeatureLayer должен быть включен в Google Cloud Console. Если FeatureLayer указанного FeatureType не существует на этой карте или стиль на основе данных недоступен (нет идентификатора карты, нет векторных листов и нет FeatureLayer , включенного в стиле карты), это регистрирует ошибку, и в результате FeatureLayer.isAvailable будет ложным. |
getHeading | getHeading() Параметры: Нет Возвращаемое значение: number|undefined Возвращает направление карты по компасу. Значение курса измеряется в градусах (по часовой стрелке) от основного направления на север. Если карта еще не инициализирована, результат undefined . |
getMapCapabilities | getMapCapabilities() Параметры: Нет Возвращаемое значение: MapCapabilities Информирует вызывающую сторону о текущих возможностях, доступных для карты, на основе предоставленного идентификатора карты. |
getMapTypeId | getMapTypeId() Параметры: Нет Возвращаемое значение: MapTypeId |string|undefined |
getProjection | getProjection() Параметры: Нет Возвращаемое значение: Projection |undefined Возвращает текущую Projection . Если карта еще не инициализирована, результат undefined . Прослушайте событие projection_changed и проверьте его значение, чтобы убедиться, что оно не является undefined . |
getRenderingType | getRenderingType() Параметры: Нет Возвращаемое значение: RenderingType Возвращает текущий RenderingType карты. |
getStreetView | getStreetView() Параметры: Нет Возвращаемое значение: StreetViewPanorama Панорама, привязанная к карте. Возвращает StreetViewPanorama по умолчанию, привязанную к карте, которая может быть панорамой по умолчанию, встроенной в карту, или панорамой, установленной с помощью setStreetView() . Изменения в streetViewControl карты будут отражены в отображении такой связанной панорамы. |
getTilt | getTilt() Параметры: Нет Возвращаемое значение: number|undefined Возвращает текущий угол наклона карты в градусах от плоскости окна просмотра к плоскости карты. Для растровых карт результатом будет 0 для изображений, сделанных прямо над головой, или 45 для изображений под углом 45°. Этот метод не возвращает значение, установленное setTilt . Подробнее см. setTilt . |
getZoom | getZoom() Параметры: Нет Возвращаемое значение: number|undefined Возвращает масштаб карты. Если масштаб не был установлен, то результат undefined . |
moveCamera | moveCamera(cameraOptions) Параметры:
Возвращаемое значение: нет Немедленно устанавливает камеру карты в параметры целевой камеры, без анимации. |
panBy | panBy(x, y) Параметры:
Возвращаемое значение: нет Изменяет центр карты на заданное расстояние в пикселях. Если расстояние меньше ширины и высоты карты, переход будет плавно анимирован. Обратите внимание, что система координат карты увеличивается с запада на восток (для значений x) и с севера на юг (для значений y). |
panTo | panTo(latLng) Параметры:
Возвращаемое значение: нет Изменяет центр карты на заданный LatLng . Если изменение меньше ширины и высоты карты, переход будет плавно анимирован. |
panToBounds | panToBounds(latLngBounds[, padding]) Параметры:
Возвращаемое значение: нет Панорамирует карту на минимальную величину, необходимую для содержания данного LatLngBounds . Это не гарантирует, где на карте будут границы, за исключением того, что карта будет панорамирована, чтобы показать как можно больше границ внутри {currentMapSizeInPx} - {padding} . Как для растровых, так и для векторных карт масштабирование, наклон и направление карты не изменяются. |
setCenter | setCenter(latlng) Параметры:
Возвращаемое значение: нет |
setClickableIcons | setClickableIcons(value) Параметры:
Возвращаемое значение: нет Определяет, кликабельны ли значки карты. Значок карты обозначает достопримечательность, также известную как POI. Чтобы отключить кликабельность значков карты, передайте этому методу значение false . |
setHeading | setHeading(heading) Параметры:
Возвращаемое значение: нет Устанавливает направление компаса для карты, измеренное в градусах от кардинального направления на север. Для растровых карт этот метод применим только к аэрофотоснимкам. |
setMapTypeId | setMapTypeId(mapTypeId) Параметры:
Возвращаемое значение: нет |
setOptions | setOptions(options) Параметры:
Возвращаемое значение: нет |
setStreetView | setStreetView(panorama) Параметры:
Возвращаемое значение: нет Привязывает StreetViewPanorama к карте. Эта панорама переопределяет StreetViewPanorama по умолчанию, позволяя карте привязываться к внешней панораме за пределами карты. Установка для панорамы значения null привязывает встроенную панораму по умолчанию обратно к карте. |
setTilt | setTilt(tilt) Параметры:
Возвращаемое значение: нет Для векторных карт задает угол падения карты. Допустимые значения ограничены в зависимости от уровня масштабирования карты. Для растровых карт управляет поведением автоматического переключения для угла падения карты. Единственными допустимыми значениями являются 0 и 45 . setTilt(0) заставляет карту всегда использовать вид сверху под углом 0° независимо от уровня масштабирования и окна просмотра. setTilt(45) заставляет угол наклона автоматически переключаться на 45 всякий раз, когда изображение под углом 45° доступно для текущего уровня масштабирования и области просмотра, и переключаться обратно на 0 всякий раз, когда изображение под углом 45° недоступно (это поведение по умолчанию). Изображения под углом 45° доступны только для satellite и hybrid типов карт, в некоторых местах и при некоторых уровнях масштабирования. Примечание: getTilt возвращает текущий угол наклона, а не значение, установленное setTilt . Поскольку getTilt и setTilt относятся к разным вещам, не bind() свойство tilt ; это может привести к непредсказуемым последствиям. |
setZoom | setZoom(zoom) Параметры:
Возвращаемое значение: нет Устанавливает масштаб карты. |
Унаследовано: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
Константы | |
---|---|
DEMO_MAP_ID | Идентификатор карты, который можно использовать для примеров кода, для которых требуется идентификатор карты. Этот идентификатор карты не предназначен для использования в рабочих приложениях и не может использоваться для функций, требующих облачной настройки (например, Cloud Styling). |
События | |
---|---|
bounds_changed | function() Аргументы: Нет Это событие запускается, когда границы области просмотра изменились. |
center_changed | function() Аргументы: Нет Это событие запускается при изменении свойства центра карты. |
click | function(event) Аргументы:
Это событие запускается, когда пользователь щелкает карту. MapMouseEvent со свойствами для выбранного местоположения возвращается, если только не был нажат значок места, и в этом случае возвращается IconMouseEvent с идентификатором места. IconMouseEvent и MapMouseEvent идентичны, за исключением того, что IconMouseEvent имеет поле идентификатора места. Событие всегда можно рассматривать как MapMouseEvent, если идентификатор места не важен. Событие щелчка не запускается, если был нажат маркер или информационное окно. |
contextmenu | function(event) Аргументы:
Это событие запускается, когда событие контекстного меню DOM запускается в контейнере карты. |
dblclick | function(event) Аргументы:
Это событие запускается, когда пользователь дважды щелкает карту. Обратите внимание, что событие щелчка иногда срабатывает один раз, а иногда и дважды, прямо перед этим. |
drag | function() Аргументы: Нет Это событие повторяется, пока пользователь перетаскивает карту. |
dragend | function() Аргументы: Нет Это событие запускается, когда пользователь перестает перетаскивать карту. |
dragstart | function() Аргументы: Нет Это событие запускается, когда пользователь начинает перетаскивать карту. |
heading_changed | function() Аргументы: Нет Это событие запускается при изменении свойства заголовка карты. |
idle | function() Аргументы: Нет Это событие запускается, когда карта становится бездействующей после панорамирования или масштабирования. |
isfractionalzoomenabled_changed | function() Аргументы: Нет Это событие запускается при изменении свойства isFractionalZoomEnabled. |
mapcapabilities_changed | function() Аргументы: Нет Это событие запускается при изменении возможностей карты. |
maptypeid_changed | function() Аргументы: Нет Это событие запускается при изменении свойства mapTypeId. |
mousemove | function(event) Аргументы:
Это событие запускается всякий раз, когда мышь пользователя перемещается по контейнеру карты. |
mouseout | function(event) Аргументы:
Это событие запускается, когда мышь пользователя выходит из контейнера карты. |
mouseover | function(event) Аргументы:
Это событие запускается, когда мышь пользователя входит в контейнер карты. |
projection_changed | function() Аргументы: Нет Это событие запускается при изменении проекции. |
renderingtype_changed | function() Аргументы: Нет Это событие запускается при изменении renderingType. |
tilesloaded | function() Аргументы: Нет Это событие запускается после завершения загрузки видимых плиток. |
tilt_changed | function() Аргументы: Нет Это событие запускается при изменении свойства наклона карты. |
zoom_changed | function() Аргументы: Нет Это событие запускается при изменении свойства масштабирования карты. |
| function(event) Аргументы:
Это событие запускается, когда пользователь щелкает правой кнопкой мыши карту. |
Интерфейс MapOptions
google.maps . MapOptions
Интерфейс google.maps . MapOptions
Объект MapOptions, используемый для определения свойств, которые можно установить на карте.
Характеристики | |
---|---|
backgroundColor optional | Тип: string optional Цвет, используемый для фона раздела карты. Этот цвет будет виден, когда плитки еще не загружены при панорамировании пользователем. Этот параметр можно установить только при инициализации карты. |
center optional | Тип: LatLng | LatLngLiteral optional Начальный центр карты. |
clickableIcons optional | Тип: boolean optional По умолчанию: true При false значки карты не кликабельны. Значок карты обозначает достопримечательность, также известную как POI. |
controlSize optional | Тип: number optional Размер в пикселях элементов управления, появляющихся на карте. Это значение должно быть указано непосредственно при создании карты, обновление этого значения позже может привести к тому, что элементы управления перейдут в undefined состояние. Управляет только элементами управления, созданными самим Maps API. Не масштабирует пользовательские элементы управления, созданные разработчиком. |
disableDefaultUI optional | Тип: boolean optional Включает/отключает все кнопки пользовательского интерфейса по умолчанию. Может быть переопределен индивидуально. Не отключает элементы управления клавиатурой, которые отдельно управляются параметром MapOptions.keyboardShortcuts . Не отключает элементы управления жестами, которые отдельно управляются параметром MapOptions.gestureHandling . |
disableDoubleClickZoom optional | Тип: boolean optional Включает/отключает масштабирование и центрирование по двойному щелчку. Включено по умолчанию. Примечание . Это свойство не рекомендуется . Чтобы отключить масштабирование при двойном щелчке, вы можете использовать |
| Тип: boolean optional Если false , запрещает перетаскивание карты. Перетаскивание включено по умолчанию. |
draggableCursor optional | Тип: string optional Имя или URL-адрес курсора, который будет отображаться при наведении курсора на карту, которую можно перетаскивать. Это свойство использует атрибут cursor css для изменения значка. Как и в случае со свойством css, вы должны указать хотя бы один резервный курсор, который не является URL-адресом. Например: draggableCursor: 'url( http://www.example.com/icon.png ), auto;' . |
draggingCursor optional | Тип: string optional Имя или URL-адрес курсора для отображения при перетаскивании карты. Это свойство использует атрибут cursor css для изменения значка. Как и в случае со свойством css, вы должны указать хотя бы один резервный курсор, который не является URL-адресом. Например: draggingCursor: 'url( http://www.example.com/icon.png ), auto;' . |
fullscreenControl optional | Тип: boolean optional Включенное/отключенное состояние полноэкранного управления. |
fullscreenControlOptions optional | Тип: FullscreenControlOptions optional Параметры отображения для полноэкранного элемента управления. |
gestureHandling optional | Тип: string optional Этот параметр определяет, как API обрабатывает жесты на карте. Допустимые значения:
|
heading optional | Тип: number optional Направление аэрофотосъемки в градусах по часовой стрелке от основного направления на север. Заголовки привязаны к ближайшему доступному углу, для которого доступно изображение. |
isFractionalZoomEnabled optional | Тип: boolean optional По умолчанию: true для векторных карт и false для растровых карт. Должна ли карта разрешать дробные уровни масштабирования. Прослушайте isfractionalzoomenabled_changed , чтобы узнать, когда было установлено значение по умолчанию. |
keyboardShortcuts optional | Тип: boolean optional Если false , запрещает управление картой с клавиатуры. Сочетания клавиш включены по умолчанию. |
mapId optional | Тип: string optional Идентификатор карты карты. Этот параметр нельзя установить или изменить после создания экземпляра карты. |
mapTypeControl optional | Тип: boolean optional Начальное включенное/отключенное состояние элемента управления «Тип карты». |
mapTypeControlOptions optional | Тип: MapTypeControlOptions optional Начальные параметры отображения для элемента управления Тип карты. |
mapTypeId optional | Тип: MapTypeId |string optional Исходный Map MapTypeId. По умолчанию ROADMAP . |
maxZoom optional | Тип: number optional Максимальный уровень масштабирования, который будет отображаться на карте. Если он опущен или установлен в null , вместо этого используется максимальное масштабирование текущего типа карты. Допустимые значения масштабирования — это числа от нуля до поддерживаемого максимального уровня масштабирования . |
minZoom optional | Тип: number optional Минимальный уровень масштабирования, который будет отображаться на карте. Если он опущен или установлен в null , вместо этого используется минимальный масштаб текущего типа карты. Допустимые значения масштабирования — это числа от нуля до поддерживаемого максимального уровня масштабирования . |
noClear optional | Тип: boolean optional Если true , не очищайте содержимое div карты. |
panControl optional | Тип: boolean optional Включенное/отключенное состояние элемента управления панорамированием. Примечание. Элемент управления Pan недоступен в новом наборе элементов управления, представленном в версии 3.22 API Google Maps JavaScript. При использовании версий 3.22 и 3.23 вы можете использовать более ранний набор элементов управления, а не новые элементы управления, что делает элемент управления панорамированием доступным как часть старого набора элементов управления. См. Что нового в элементах управления картой версии 3.22 . |
panControlOptions optional | Тип: PanControlOptions optional Параметры отображения для элемента управления панорамированием. Примечание. Элемент управления Pan недоступен в новом наборе элементов управления, представленном в версии 3.22 API Google Maps JavaScript. При использовании версий 3.22 и 3.23 вы можете использовать более ранний набор элементов управления, а не новые элементы управления, что делает элемент управления панорамированием доступным как часть старого набора элементов управления. См. Что нового в элементах управления картой версии 3.22 . |
restriction optional | Тип: MapRestriction optional Определяет границу, которая ограничивает область карты, доступную для пользователей. Когда установлено, пользователь может только панорамировать и масштабировать, пока вид камеры остается в пределах границ. |
rotateControl optional | Тип: boolean optional Включенное/отключенное состояние элемента управления Rotate. |
rotateControlOptions optional | Тип: RotateControlOptions optional Параметры отображения для элемента управления поворотом. |
scaleControl optional | Тип: boolean optional Начальное включенное/выключенное состояние элемента управления Scale. |
scaleControlOptions optional | Тип: ScaleControlOptions optional Начальные параметры отображения для элемента управления Масштаб. |
scrollwheel optional | Тип: boolean optional При значении false отключает масштабирование карты с помощью колеса прокрутки мыши. Колесо прокрутки включено по умолчанию. Примечание . Это свойство не рекомендуется . Чтобы отключить масштабирование с помощью колеса прокрутки, вы можете использовать |
streetView optional | Тип: StreetViewPanorama optional StreetViewPanorama , отображаемая, когда человечек Просмотра улиц перетаскивается на карту. Если панорама не указана, StreetViewPanorama по умолчанию будет отображаться в div карты, когда человечек перетаскивается. |
streetViewControl optional | Тип: boolean optional Начальное включенное/отключенное состояние элемента управления Pegman в Просмотре улиц. Этот элемент управления является частью пользовательского интерфейса по умолчанию, и для него следует установить значение false при отображении типа карты, на котором не должно отображаться наложение дорог в Просмотре улиц (например, тип карты, отличный от Земли). |
streetViewControlOptions optional | Тип: StreetViewControlOptions optional Начальные параметры отображения для элемента управления Pegman в Просмотре улиц. |
styles optional | Тип: Array < MapTypeStyle > optional Стили, применяемые к каждому из типов карт по умолчанию. Обратите внимание, что для satellite / hybrid и terrain режимов эти стили будут применяться только к надписям и геометрии. |
tilt optional | Тип: number optional Для векторных карт задает угол падения карты. Допустимые значения ограничены в зависимости от уровня масштабирования карты. Для растровых карт управляет поведением автоматического переключения для угла падения карты. Единственными допустимыми значениями являются 0 и 45 . Значение 0 заставляет карту всегда использовать вид сверху под углом 0° независимо от уровня масштабирования и окна просмотра. Значение 45 приводит к тому, что угол наклона автоматически переключается на 45 всякий раз, когда для текущего уровня масштабирования и окна просмотра доступно изображение под углом 45°, и переключается обратно на 0, когда изображение под углом 45° недоступно (это поведение по умолчанию). Изображения под углом 45° доступны только для satellite и hybrid типов карт, в некоторых местах и при некоторых уровнях масштабирования. Примечание: getTilt возвращает текущий угол наклона, а не значение, заданное этой опцией. Поскольку getTilt и этот параметр относятся к разным вещам, не bind() свойство tilt ; это может привести к непредсказуемым последствиям. |
zoom optional | Тип: number optional Начальный уровень масштабирования карты. Допустимые значения масштабирования — это числа от нуля до поддерживаемого максимального уровня масштабирования . Большие значения масштабирования соответствуют более высокому разрешению. |
zoomControl optional | Тип: boolean optional Включенное/отключенное состояние элемента управления масштабированием. |
zoomControlOptions optional | Тип: ZoomControlOptions optional Параметры отображения для элемента управления масштабированием. |
Класс MapElement
google.maps . MapElement
Класс google.maps . MapElement
MapElement — это подкласс HTMLElement
для рендеринга карт. После загрузки библиотеки maps
можно создать карту в формате HTML. Например:
<gmp-map center="37.4220656,-122.0840897" zoom="10" map-id="DEMO_MAP_ID"></gmp-map>
Внутри он использует Map
, доступ к которому можно получить с помощью свойства innerMap
.
Пользовательский элемент:
<gmp-map center="lat,lng" map-id="string" zoom="number"></gmp-map>
Этот класс расширяет HTMLElement
.
Этот класс реализует MapElementOptions
.
Получите доступ, вызвав const {MapElement} = await google.maps.importLibrary("maps")
. См. Библиотеки в Maps JavaScript API .
Характеристики | |
---|---|
center | Тип: LatLng | LatLngLiteral optional HTML-атрибут:
|
innerMap | Тип: Map Ссылка на Map , которую MapElement использует внутри. |
mapId | Тип: string optional HTML-атрибут:
|
zoom | Тип: number optional HTML-атрибут:
|
Методы | |
---|---|
addEventListener | addEventListener(type, listener[, options]) Параметры:
Возвращаемое значение: void Настраивает функцию, которая будет вызываться всякий раз, когда указанное событие доставляется цели. См. addEventListener |
removeEventListener | removeEventListener(type, listener[, options]) Параметры:
Возвращаемое значение: void Удаляет прослушиватель событий, ранее зарегистрированный с помощью addEventListener, из цели. См. RemoveEventListener |
Интерфейс MapElementOptions
google.maps . MapElementOptions
Интерфейс google.maps . MapElementOptions
Объект MapElementOptions, используемый для определения свойств, которые можно задать для MapElement.
Характеристики | |
---|---|
center optional | Тип: LatLng | LatLngLiteral optional Начальный центр карты. |
mapId optional | Тип: string optional Идентификатор карты карты. Этот параметр нельзя установить или изменить после создания экземпляра карты. |
zoom optional | Тип: number optional Начальный уровень масштабирования карты. Допустимые значения масштабирования — это числа от нуля до поддерживаемого максимального уровня масштабирования . Большие значения масштабирования соответствуют более высокому разрешению. |
Интерфейс MapTypeStyle
google.maps . MapTypeStyle
Интерфейс google.maps . MapTypeStyle
MapTypeStyle
— это набор селекторов и стилей, которые определяют стиль карты. Селекторы определяют функции и/или элементы карты, на которые следует воздействовать, а стили указывают, как следует изменять эти функции и элементы. Подробнее см. в справочнике по стилю .
Характеристики | |
---|---|
stylers | Правила стиля, применяемые к выбранным объектам и элементам карты. Правила применяются в том порядке, который вы указываете в этом массиве. Рекомендации по использованию и допустимые значения см. в справочнике по стилю . |
elementType optional | Тип: string optional Элемент, к которому следует применить стиль. Элемент — это визуальный аспект объекта на карте. Пример: метка, значок, обводка или заливка, примененные к геометрии, и многое другое. Необязательный. Если elementType не указан, предполагается, что значение равно 'all' . Подробнее об использовании и допустимых значениях см. в справочнике по стилю . |
featureType optional | Тип: string optional Элемент или группа элементов, к которым следует применить стиль. Необязательный. Если featureType не указан, предполагается, что значение равно 'all' . Подробнее об использовании и допустимых значениях см. в справочнике по стилю . |
Интерфейс MapMouseEvent
google.maps . MapMouseEvent
Интерфейс google.maps . MapMouseEvent
Этот объект возвращается из различных событий мыши на карте и наложениях и содержит все поля, показанные ниже.
Характеристики | |
---|---|
domEvent | Тип: MouseEvent | TouchEvent | PointerEvent | KeyboardEvent | Event Соответствующее собственное событие DOM. Разработчики не должны полагаться на то, что свойства target , currentTarget , relatedTarget и path определены и непротиворечивы. Разработчикам также не следует полагаться на структуру DOM внутренней реализации Maps API. Из-за внутреннего сопоставления событий domEvent может отличаться от семантики MapMouseEvent (например, «щелчок» MapMouseEvent может иметь domEvent типа KeyboardEvent ). |
latLng optional | Тип: LatLng optional Широта/долгота, которые были ниже курсора, когда произошло событие. |
Методы | |
---|---|
stop | stop() Параметры: Нет Возвращаемое значение: void Предотвращает дальнейшее распространение этого события. |
Интерфейс IconMouseEvent
google.maps . IconMouseEvent
Интерфейс google.maps . IconMouseEvent
Этот объект отправляется в событии, когда пользователь щелкает значок на карте. Идентификатор места этого места хранится в элементе placeId. Чтобы информационное окно по умолчанию не отображалось, вызовите метод stop() для этого события, чтобы предотвратить его распространение. Узнайте больше об идентификаторах мест в руководстве для разработчиков Places API.
Этот интерфейс расширяет MapMouseEvent
.
Характеристики | |
---|---|
placeId optional | Тип: string optional Идентификатор места, на которое нажали. Этот идентификатор места можно использовать для запроса дополнительной информации о выбранном объекте. Узнайте больше об идентификаторах мест в руководстве для разработчиков Places API. |
Унаследовано: domEvent , latLng |
Методы | |
---|---|
Унаследовано: stop |
Константы MapTypeId
google.maps . MapTypeId
Константы google.maps . MapTypeId
Идентификаторы для общих типов карт. Укажите их по значению или по имени константы. Например, 'satellite'
или google.maps.MapTypeId.SATELLITE
.
Получите доступ, вызвав const {MapTypeId} = await google.maps.importLibrary("maps")
. См. Библиотеки в Maps JavaScript API .
Константы | |
---|---|
HYBRID | Этот тип карты отображает прозрачный слой основных улиц на спутниковых снимках. |
ROADMAP | Этот тип карты отображает обычную карту улиц. |
SATELLITE | Этот тип карты отображает спутниковые изображения. |
TERRAIN | Этот тип карты отображает карты с физическими характеристиками, такими как рельеф и растительность. |
Класс MapTypeRegistry
google.maps . MapTypeRegistry
Класс google.maps . MapTypeRegistry
Реестр для экземпляров MapType с ключом по идентификатору MapType.
Этот класс расширяет MVCObject
.
Получите доступ, вызвав const {MapTypeRegistry} = await google.maps.importLibrary("maps")
. См. Библиотеки в Maps JavaScript API .
Конструктор | |
---|---|
MapTypeRegistry | MapTypeRegistry() Параметры: Нет MapTypeRegistry содержит коллекцию пользовательских типов карт, доступных для использования картой. API обращается к этому реестру, например, при предоставлении списка доступных типов карт в элементах управления. |
Методы | |
---|---|
set | set(id, mapType) Параметры:
Возвращаемое значение: нет Задает для реестра связь переданного строкового идентификатора с переданным MapType. |
Унаследовано: addListener , bindTo , get , notify , setValues , unbind , unbindAll |
Интерфейс MapRestriction
google.maps . MapRestriction
Интерфейс google.maps . MapRestriction
Ограничение, которое может быть применено к Карте. Окно просмотра карты не будет выходить за эти ограничения.
Характеристики | |
---|---|
latLngBounds | Тип: LatLngBounds | LatLngBoundsLiteral Когда установлено, пользователь может панорамировать и масштабировать только в пределах заданных границ. Границы могут ограничивать как долготу, так и широту, или могут ограничивать только широту. Для границ только по широте используйте западную и восточную долготы -180 и 180 соответственно, например, latLngBounds: {north: northLat, south: southLat, west: -180, east: 180} . |
strictBounds optional | Тип: boolean optional Границы можно сделать более строгими, установив для флага strictBounds значение true . Это уменьшает масштаб, на который пользователь может уменьшить масштаб, гарантируя, что все, что находится за пределами ограниченных границ, останется скрытым. Значение по умолчанию — false , что означает, что пользователь может уменьшать масштаб до тех пор, пока не будет видна вся ограниченная область, возможно, включая области за пределами ограниченной области. |
Класс TrafficLayer
google.maps . TrafficLayer
Класс google.maps . TrafficLayer
Слой трафика.
Этот класс расширяет MVCObject
.
Получите доступ, вызвав const {TrafficLayer} = await google.maps.importLibrary("maps")
. См. Библиотеки в Maps JavaScript API .
Конструктор | |
---|---|
TrafficLayer | TrafficLayer([opts]) Параметры:
Слой, отображающий текущий дорожный трафик. |
Методы | |
---|---|
getMap | getMap() Параметры: Нет Возвращаемое значение: Map Возвращает карту, на которой отображается этот слой. |
setMap | setMap(map) Параметры:
Возвращаемое значение: нет Визуализирует слой на указанной карте. Если для карты задано значение null , слой будет удален. |
setOptions | setOptions(options) Параметры:
Возвращаемое значение: нет |
Унаследовано: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
Интерфейс TrafficLayerOptions
google.maps . TrafficLayerOptions
Интерфейс google.maps . TrafficLayerOptions
Объект TrafficLayerOptions, используемый для определения свойств, которые можно задать для TrafficLayer.
Характеристики | |
---|---|
autoRefresh optional | Тип: boolean optional По умолчанию: true Обновляется ли уровень трафика с обновленной информацией автоматически. |
map optional | Тип: Map optional Карта, на которой отображать слой трафика. |
Класс TransitLayer
google.maps . TransitLayer
Класс google.maps . TransitLayer
Транзитный слой.
Этот класс расширяет MVCObject
.
Получите доступ, вызвав const {TransitLayer} = await google.maps.importLibrary("maps")
. См. Библиотеки в Maps JavaScript API .
Конструктор | |
---|---|
TransitLayer | TransitLayer() Параметры: Нет Слой, отображающий линии общественного транспорта. |
Методы | |
---|---|
getMap | getMap() Параметры: Нет Возвращаемое значение: Map Возвращает карту, на которой отображается этот слой. |
setMap | setMap(map) Параметры:
Возвращаемое значение: нет Визуализирует слой на указанной карте. Если для карты задано значение null , слой будет удален. |
Унаследовано: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
Класс BicyclingLayer
google.maps . BicyclingLayer
Класс google.maps . BicyclingLayer
Слой, показывающий велосипедные дорожки и дорожки.
Этот класс расширяет MVCObject
.
Получите доступ, вызвав const {BicyclingLayer} = await google.maps.importLibrary("maps")
. См. Библиотеки в Maps JavaScript API .
Конструктор | |
---|---|
BicyclingLayer | BicyclingLayer() Параметры: Нет Слой, который отображает велосипедные дорожки и дорожки и понижает большие дороги. |
Методы | |
---|---|
getMap | getMap() Параметры: Нет Возвращаемое значение: Map Возвращает карту, на которой отображается этот слой. |
setMap | setMap(map) Параметры:
Возвращаемое значение: нет Визуализирует слой на указанной карте. Если для карты задано значение null , слой будет удален. |
Унаследовано: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
Интерфейс опций камеры
google.maps . CameraOptions
Интерфейс google.maps . CameraOptions
Используется для настройки параметров камеры карты.
Характеристики | |
---|---|
center optional | Тип: LatLngLiteral | LatLng optional |
heading optional | Тип: number optional |
tilt optional | Тип: number optional |
zoom optional | Тип: number optional |
Интерфейс видимой области
google.maps . VisibleRegion
Интерфейс google.maps . VisibleRegion
Содержит четыре точки, определяющие четырехсторонний многоугольник, который является видимой областью карты. На векторной карте этот многоугольник может быть трапецией, а не прямоугольником, когда векторная карта имеет наклон.
Характеристики | |
---|---|
farLeft | Тип: LatLng |
farRight | Тип: LatLng |
latLngBounds | Тип: LatLngBounds Наименьшая ограничивающая рамка, включающая видимую область. |
nearLeft | Тип: LatLng |
nearRight | Тип: LatLng |
Константы RenderingType
google.maps . RenderingType
Константы google.maps . RenderingType
Получите доступ, вызвав const {RenderingType} = await google.maps.importLibrary("maps")
. См. Библиотеки в Maps JavaScript API .
Константы | |
---|---|
RASTER | Указывает, что карта является растровой. |
UNINITIALIZED | Указывает, что пока неизвестно, является ли карта векторной или растровой, поскольку инициализация карты еще не завершена. |
VECTOR | Указывает, что карта является векторной картой. |
Интерфейс MapCapabilities
google.maps . MapCapabilities
Интерфейс google.maps . MapCapabilities
Объект, содержащий снимок того, какие возможности в настоящее время доступны для Карты. Note that this does not necessarily mean that relevant modules are loaded or initialized, but rather that the current map has permission to use these APIs. See the properties for a list of possible capabilities.
Properties | |
---|---|
isAdvancedMarkersAvailable optional | Type: boolean optional If true, this map is configured properly to allow for the use of advanced markers. Note that you must still import the marker library in order to use advanced markers. See https://goo.gle/gmp-isAdvancedMarkersAvailable for more information. |
isDataDrivenStylingAvailable optional | Type: boolean optional If true, this map is configured properly to allow for the use of data-driven styling for at least one FeatureLayer. See https://goo.gle/gmp-data-driven-styling and https://goo.gle/gmp-FeatureLayerIsAvailable for more information. |
Map class
google.maps . Map
class
This class extends MVCObject
.
Access by calling const {Map} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
Map | Map(mapDiv[, opts]) Parameters:
Creates a new map inside of the given HTML container, which is typically a DIV element. |
Properties | |
---|---|
controls | Type: Array < MVCArray < HTMLElement >> Additional controls to attach to the map. To add a control to the map, add the control's <div> to the MVCArray corresponding to the ControlPosition where it should be rendered. |
data | Type: Data An instance of Data , bound to the map. Add features to this Data object to conveniently display them on this map. |
mapTypes | Type: MapTypeRegistry A registry of MapType instances by string ID. |
overlayMapTypes | Additional map types to overlay. Overlay map types will display on top of the base map they are attached to, in the order in which they appear in the overlayMapTypes array (overlays with higher index values are displayed in front of overlays with lower index values). |
Methods | |
---|---|
fitBounds | fitBounds(bounds[, padding]) Parameters:
Return Value: None Sets the viewport to contain the given bounds. Note: When the map is set to display: none , the fitBounds function reads the map's size as 0x0, and therefore does not do anything. To change the viewport while the map is hidden, set the map to visibility: hidden , thereby ensuring the map div has an actual size. For vector maps, this method sets the map's tilt and heading to their default zero values. Calling this method may cause a smooth animation as the map pans and zooms to fit the bounds. Whether or not this method animates depends on an internal heuristic. |
getBounds | getBounds() Parameters: None Return Value: LatLngBounds |undefined The lat/lng bounds of the current viewport. Returns the lat/lng bounds of the current viewport. If more than one copy of the world is visible, the bounds range in longitude from -180 to 180 degrees inclusive. If the map is not yet initialized or center and zoom have not been set then the result is undefined . For vector maps with non-zero tilt or heading, the returned lat/lng bounds represents the smallest bounding box that includes the visible region of the map's viewport. See MapCanvasProjection.getVisibleRegion for getting the exact visible region of the map's viewport. |
getCenter | getCenter() Parameters: None Return Value: LatLng |undefined |
getClickableIcons | getClickableIcons() Parameters: None Return Value: boolean|undefined Returns the clickability of the map icons. A map icon represents a point of interest, also known as a POI. If the returned value is true , then the icons are clickable on the map. |
getDatasetFeatureLayer | getDatasetFeatureLayer(datasetId) Parameters:
Return Value: FeatureLayer Returns the FeatureLayer for the specified datasetId . Dataset IDs must be configured in the Google Cloud Console. If the dataset ID is not associated with the map's map style, or if Data-driven styling is not available (no map ID, no vector tiles, no Data-Driven Styling feature layers or Datasets configured in the Map Style), this logs an error, and the resulting FeatureLayer.isAvailable will be false. |
getDiv | getDiv() Parameters: None Return Value: HTMLElement The mapDiv of the map. |
getFeatureLayer | getFeatureLayer(featureType) Parameters:
Return Value: FeatureLayer Returns the FeatureLayer of the specific FeatureType . A FeatureLayer must be enabled in the Google Cloud Console. If a FeatureLayer of the specified FeatureType does not exist on this map, or if Data-driven styling is not available (no map ID, no vector tiles, and no FeatureLayer enabled in the map style), this logs an error, and the resulting FeatureLayer.isAvailable will be false. |
getHeading | getHeading() Parameters: None Return Value: number|undefined Returns the compass heading of the map. The heading value is measured in degrees (clockwise) from cardinal direction North. If the map is not yet initialized then the result is undefined . |
getMapCapabilities | getMapCapabilities() Parameters: None Return Value: MapCapabilities Informs the caller of the current capabilities available to the map based on the Map ID that was provided. |
getMapTypeId | getMapTypeId() Parameters: None Return Value: MapTypeId |string|undefined |
getProjection | getProjection() Parameters: None Return Value: Projection |undefined Returns the current Projection . If the map is not yet initialized then the result is undefined . Listen to the projection_changed event and check its value to ensure it is not undefined . |
getRenderingType | getRenderingType() Parameters: None Return Value: RenderingType Returns the current RenderingType of the map. |
getStreetView | getStreetView() Parameters: None Return Value: StreetViewPanorama The panorama bound to the map. Returns the default StreetViewPanorama bound to the map, which may be a default panorama embedded within the map, or the panorama set using setStreetView() . Changes to the map's streetViewControl will be reflected in the display of such a bound panorama. |
getTilt | getTilt() Parameters: None Return Value: number|undefined Returns the current angle of incidence of the map, in degrees from the viewport plane to the map plane. For raster maps, the result will be 0 for imagery taken directly overhead or 45 for 45° imagery. This method does not return the value set by setTilt . See setTilt for details. |
getZoom | getZoom() Parameters: None Return Value: number|undefined Returns the zoom of the map. If the zoom has not been set then the result is undefined . |
moveCamera | moveCamera(cameraOptions) Parameters:
Return Value: None Immediately sets the map's camera to the target camera options, without animation. |
panBy | panBy(x, y) Parameters:
Return Value: None Changes the center of the map by the given distance in pixels. If the distance is less than both the width and height of the map, the transition will be smoothly animated. Note that the map coordinate system increases from west to east (for x values) and north to south (for y values). |
panTo | panTo(latLng) Parameters:
Return Value: None Changes the center of the map to the given LatLng . If the change is less than both the width and height of the map, the transition will be smoothly animated. |
panToBounds | panToBounds(latLngBounds[, padding]) Parameters:
Return Value: None Pans the map by the minimum amount necessary to contain the given LatLngBounds . It makes no guarantee where on the map the bounds will be, except that the map will be panned to show as much of the bounds as possible inside {currentMapSizeInPx} - {padding} . For both raster and vector maps, the map's zoom, tilt, and heading will not be changed. |
setCenter | setCenter(latlng) Parameters:
Return Value: None |
setClickableIcons | setClickableIcons(value) Parameters:
Return Value: None Controls whether the map icons are clickable or not. A map icon represents a point of interest, also known as a POI. To disable the clickability of map icons, pass a value of false to this method. |
setHeading | setHeading(heading) Parameters:
Return Value: None Sets the compass heading for map measured in degrees from cardinal direction North. For raster maps, this method only applies to aerial imagery. |
setMapTypeId | setMapTypeId(mapTypeId) Parameters:
Return Value: None |
setOptions | setOptions(options) Parameters:
Return Value: None |
setStreetView | setStreetView(panorama) Parameters:
Return Value: None Binds a StreetViewPanorama to the map. This panorama overrides the default StreetViewPanorama , allowing the map to bind to an external panorama outside of the map. Setting the panorama to null binds the default embedded panorama back to the map. |
setTilt | setTilt(tilt) Parameters:
Return Value: None For vector maps, sets the angle of incidence of the map. The allowed values are restricted depending on the zoom level of the map. For raster maps, controls the automatic switching behavior for the angle of incidence of the map. The only allowed values are 0 and 45 . setTilt(0) causes the map to always use a 0° overhead view regardless of the zoom level and viewport. setTilt(45) causes the tilt angle to automatically switch to 45 whenever 45° imagery is available for the current zoom level and viewport, and switch back to 0 whenever 45° imagery is not available (this is the default behavior). 45° imagery is only available for satellite and hybrid map types, within some locations, and at some zoom levels. Note: getTilt returns the current tilt angle, not the value set by setTilt . Because getTilt and setTilt refer to different things, do not bind() the tilt property; doing so may yield unpredictable effects. |
setZoom | setZoom(zoom) Parameters:
Return Value: None Sets the zoom of the map. |
Inherited: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
Constants | |
---|---|
DEMO_MAP_ID | Map ID which can be used for code samples which require a Map ID. This Map ID is not intended for use in production applications and cannot be used for features which require cloud configuration (such as Cloud Styling). |
События | |
---|---|
bounds_changed | function() Arguments: None This event is fired when the viewport bounds have changed. |
center_changed | function() Arguments: None This event is fired when the map center property changes. |
click | function(event) Arguments:
This event is fired when the user clicks on the map. A MapMouseEvent with properties for the clicked location is returned unless a place icon was clicked, in which case an IconMouseEvent with a place ID is returned. IconMouseEvent and MapMouseEvent are identical, except that IconMouseEvent has the place ID field. The event can always be treated as an MapMouseEvent when the place ID is not important. The click event is not fired if a marker or info window was clicked. |
contextmenu | function(event) Arguments:
This event is fired when the DOM contextmenu event is fired on the map container. |
dblclick | function(event) Arguments:
This event is fired when the user double-clicks on the map. Note that the click event will sometimes fire once and sometimes twice, right before this one. |
drag | function() Arguments: None This event is repeatedly fired while the user drags the map. |
dragend | function() Arguments: None This event is fired when the user stops dragging the map. |
dragstart | function() Arguments: None This event is fired when the user starts dragging the map. |
heading_changed | function() Arguments: None This event is fired when the map heading property changes. |
idle | function() Arguments: None This event is fired when the map becomes idle after panning or zooming. |
isfractionalzoomenabled_changed | function() Arguments: None This event is fired when the isFractionalZoomEnabled property has changed. |
mapcapabilities_changed | function() Arguments: None This event is fired when the map capabilities change. |
maptypeid_changed | function() Arguments: None This event is fired when the mapTypeId property changes. |
mousemove | function(event) Arguments:
This event is fired whenever the user's mouse moves over the map container. |
mouseout | function(event) Arguments:
This event is fired when the user's mouse exits the map container. |
mouseover | function(event) Arguments:
This event is fired when the user's mouse enters the map container. |
projection_changed | function() Arguments: None This event is fired when the projection has changed. |
renderingtype_changed | function() Arguments: None This event is fired when the renderingType has changed. |
tilesloaded | function() Arguments: None This event is fired when the visible tiles have finished loading. |
tilt_changed | function() Arguments: None This event is fired when the map tilt property changes. |
zoom_changed | function() Arguments: None This event is fired when the map zoom property changes. |
| function(event) Arguments:
This event is fired when the user right-clicks on the map. |
MapOptions interface
google.maps . MapOptions
interface
MapOptions object used to define the properties that can be set on a Map.
Properties | |
---|---|
backgroundColor optional | Type: string optional Color used for the background of the Map div. This color will be visible when tiles have not yet loaded as the user pans. This option can only be set when the map is initialized. |
center optional | Type: LatLng | LatLngLiteral optional The initial Map center. |
clickableIcons optional | Type: boolean optional Default: true When false , map icons are not clickable. A map icon represents a point of interest, also known as a POI. |
controlSize optional | Type: number optional Size in pixels of the controls appearing on the map. This value must be supplied directly when creating the Map, updating this value later may bring the controls into an undefined state. Only governs the controls made by the Maps API itself. Does not scale developer created custom controls. |
disableDefaultUI optional | Type: boolean optional Enables/disables all default UI buttons. May be overridden individually. Does not disable the keyboard controls, which are separately controlled by the MapOptions.keyboardShortcuts option. Does not disable gesture controls, which are separately controlled by the MapOptions.gestureHandling option. |
disableDoubleClickZoom optional | Type: boolean optional Enables/disables zoom and center on double click. Enabled by default. Note : This property is not recommended . To disable zooming on double click, you can use the |
| Type: boolean optional If false , prevents the map from being dragged. Dragging is enabled by default. |
draggableCursor optional | Type: string optional The name or url of the cursor to display when mousing over a draggable map. This property uses the css cursor attribute to change the icon. As with the css property, you must specify at least one fallback cursor that is not a URL. For example: draggableCursor: 'url( http://www.example.com/icon.png ), auto;' . |
draggingCursor optional | Type: string optional The name or url of the cursor to display when the map is being dragged. This property uses the css cursor attribute to change the icon. As with the css property, you must specify at least one fallback cursor that is not a URL. For example: draggingCursor: 'url( http://www.example.com/icon.png ), auto;' . |
fullscreenControl optional | Type: boolean optional The enabled/disabled state of the Fullscreen control. |
fullscreenControlOptions optional | Type: FullscreenControlOptions optional The display options for the Fullscreen control. |
gestureHandling optional | Type: string optional This setting controls how the API handles gestures on the map. Allowed values:
|
heading optional | Type: number optional The heading for aerial imagery in degrees measured clockwise from cardinal direction North. Headings are snapped to the nearest available angle for which imagery is available. |
isFractionalZoomEnabled optional | Type: boolean optional Default: true for vector maps and false for raster maps Whether the map should allow fractional zoom levels. Listen to isfractionalzoomenabled_changed to know when the default has been set. |
keyboardShortcuts optional | Type: boolean optional If false , prevents the map from being controlled by the keyboard. Keyboard shortcuts are enabled by default. |
mapId optional | Type: string optional The Map ID of the map. This parameter cannot be set or changed after a map is instantiated. |
mapTypeControl optional | Type: boolean optional The initial enabled/disabled state of the Map type control. |
mapTypeControlOptions optional | Type: MapTypeControlOptions optional The initial display options for the Map type control. |
mapTypeId optional | Type: MapTypeId |string optional The initial Map mapTypeId. Defaults to ROADMAP . |
maxZoom optional | Type: number optional The maximum zoom level which will be displayed on the map. If omitted, or set to null , 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 . |
minZoom optional | Type: number optional The minimum zoom level which will be displayed on the map. If omitted, or set to null , 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 . |
noClear optional | Type: boolean optional If true , do not clear the contents of the Map div. |
panControl optional | Type: boolean optional The enabled/disabled state of the Pan control. Note: The Pan control is not available in the new set of controls introduced in v3.22 of the Google Maps JavaScript API. While using v3.22 and v3.23, you can choose to use the earlier set of controls rather than the new controls, thus making the Pan control available as part of the old control set. See What's New in the v3.22 Map Controls . |
panControlOptions optional | Type: PanControlOptions optional The display options for the Pan control. Note: The Pan control is not available in the new set of controls introduced in v3.22 of the Google Maps JavaScript API. While using v3.22 and v3.23, you can choose to use the earlier set of controls rather than the new controls, thus making the Pan control available as part of the old control set. See What's New in the v3.22 Map Controls . |
restriction optional | Type: MapRestriction optional Defines a boundary that restricts the area of the map accessible to users. When set, a user can only pan and zoom while the camera view stays inside the limits of the boundary. |
rotateControl optional | Type: boolean optional The enabled/disabled state of the Rotate control. |
rotateControlOptions optional | Type: RotateControlOptions optional The display options for the Rotate control. |
scaleControl optional | Type: boolean optional The initial enabled/disabled state of the Scale control. |
scaleControlOptions optional | Type: ScaleControlOptions optional The initial display options for the Scale control. |
scrollwheel optional | Type: boolean optional If false , disables zooming on the map using a mouse scroll wheel. The scrollwheel is enabled by default. Note : This property is not recommended . To disable zooming using scrollwheel, you can use the |
streetView optional | Type: StreetViewPanorama optional A StreetViewPanorama to display when the Street View pegman is dropped on the map. If no panorama is specified, a default StreetViewPanorama will be displayed in the map's div when the pegman is dropped. |
streetViewControl optional | Type: boolean optional The initial enabled/disabled state of the Street View Pegman control. This control is part of the default UI, and should be set to false when displaying a map type on which the Street View road overlay should not appear (eg a non-Earth map type). |
streetViewControlOptions optional | Type: StreetViewControlOptions optional The initial display options for the Street View Pegman control. |
styles optional | Type: Array < MapTypeStyle > optional Styles to apply to each of the default map types. Note that for satellite / hybrid and terrain modes, these styles will only apply to labels and geometry. |
tilt optional | Type: number optional For vector maps, sets the angle of incidence of the map. The allowed values are restricted depending on the zoom level of the map. For raster maps, controls the automatic switching behavior for the angle of incidence of the map. The only allowed values are 0 and 45 . The value 0 causes the map to always use a 0° overhead view regardless of the zoom level and viewport. The value 45 causes the tilt angle to automatically switch to 45 whenever 45° imagery is available for the current zoom level and viewport, and switch back to 0 whenever 45° imagery is not available (this is the default behavior). 45° imagery is only available for satellite and hybrid map types, within some locations, and at some zoom levels. Note: getTilt returns the current tilt angle, not the value specified by this option. Because getTilt and this option refer to different things, do not bind() the tilt property; doing so may yield unpredictable effects. |
zoom optional | Type: number optional The initial Map zoom level. Valid zoom values are numbers from zero up to the supported maximum zoom level . Larger zoom values correspond to a higher resolution. |
zoomControl optional | Type: boolean optional The enabled/disabled state of the Zoom control. |
zoomControlOptions optional | Type: ZoomControlOptions optional The display options for the Zoom control. |
MapElement class
google.maps . MapElement
class
MapElement is an HTMLElement
subclass for rendering maps. After loading the maps
library, a map can be created in HTML. Например:
<gmp-map center="37.4220656,-122.0840897" zoom="10" map-id="DEMO_MAP_ID"></gmp-map>
Internally, it uses Map
, which can be accessed with the innerMap
property.
Custom element:
<gmp-map center="lat,lng" map-id="string" zoom="number"></gmp-map>
This class extends HTMLElement
.
This class implements MapElementOptions
.
Access by calling const {MapElement} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Properties | |
---|---|
center | Type: LatLng | LatLngLiteral optional HTML attribute:
|
innerMap | Type: Map A reference to the Map that the MapElement uses internally. |
mapId | Type: string optional HTML attribute:
|
zoom | Type: number optional HTML attribute:
|
Methods | |
---|---|
addEventListener | addEventListener(type, listener[, options]) Parameters:
Return Value: void Sets up a function that will be called whenever the specified event is delivered to the target. See addEventListener |
removeEventListener | removeEventListener(type, listener[, options]) Parameters:
Return Value: void Removes an event listener previously registered with addEventListener from the target. See removeEventListener |
MapElementOptions interface
google.maps . MapElementOptions
interface
MapElementOptions object used to define the properties that can be set on a MapElement.
Properties | |
---|---|
center optional | Type: LatLng | LatLngLiteral optional The initial Map center. |
mapId optional | Type: string optional The Map ID of the map. This parameter cannot be set or changed after a map is instantiated. |
zoom optional | Type: number optional The initial Map zoom level. Valid zoom values are numbers from zero up to the supported maximum zoom level . Larger zoom values correspond to a higher resolution. |
MapTypeStyle interface
google.maps . MapTypeStyle
interface
The MapTypeStyle
is a collection of selectors and stylers that define how the map should be styled. Selectors specify the map features and/or elements that should be affected, and stylers specify how those features and elements should be modified. For details, see the style reference .
Properties | |
---|---|
stylers | The style rules to apply to the selected map features and elements. The rules are applied in the order that you specify in this array. For guidelines on usage and allowed values, see the style reference . |
elementType optional | Type: string optional The element to which a styler should be applied. An element is a visual aspect of a feature on the map. Example: a label, an icon, the stroke or fill applied to the geometry, and more. Optional. If elementType is not specified, the value is assumed to be 'all' . For details of usage and allowed values, see the style reference . |
featureType optional | Type: string optional The feature, or group of features, to which a styler should be applied. Optional. If featureType is not specified, the value is assumed to be 'all' . For details of usage and allowed values, see the style reference . |
MapMouseEvent interface
google.maps . MapMouseEvent
interface
This object is returned from various mouse events on the map and overlays, and contains all the fields shown below.
Properties | |
---|---|
domEvent | Type: MouseEvent | TouchEvent | PointerEvent | KeyboardEvent | Event The corresponding native DOM event. Developers should not rely on target , currentTarget , relatedTarget and path properties being defined and consistent. Developers should not also rely on the DOM structure of the internal implementation of the Maps API. Due to internal event mapping, the domEvent may have different semantics from the MapMouseEvent (eg a MapMouseEvent "click" may have a domEvent of type KeyboardEvent ). |
latLng optional | Type: LatLng optional The latitude/longitude that was below the cursor when the event occurred. |
Methods | |
---|---|
stop | stop() Parameters: None Return Value: void Prevents this event from propagating further. |
IconMouseEvent interface
google.maps . IconMouseEvent
interface
This object is sent in an event when a user clicks on an icon on the map. The place ID of this place is stored in the placeId member. To prevent the default info window from showing up, call the stop() method on this event to prevent it being propagated. Learn more about place IDs in the Places API developer guide.
This interface extends MapMouseEvent
.
Properties | |
---|---|
placeId optional | Type: string optional The place ID of the place that was clicked. This place ID can be used to query more information about the feature that was clicked. Learn more about place IDs in the Places API developer guide. |
Inherited: domEvent , latLng |
Methods | |
---|---|
Inherited: stop |
MapTypeId constants
google.maps . MapTypeId
constants
Identifiers for common MapTypes. Specify these by value, or by using the constant's name. For example, 'satellite'
or google.maps.MapTypeId.SATELLITE
.
Access by calling const {MapTypeId} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constants | |
---|---|
HYBRID | This map type displays a transparent layer of major streets on satellite images. |
ROADMAP | This map type displays a normal street map. |
SATELLITE | This map type displays satellite images. |
TERRAIN | This map type displays maps with physical features such as terrain and vegetation. |
MapTypeRegistry class
google.maps . MapTypeRegistry
class
A registry for MapType instances, keyed by MapType id.
This class extends MVCObject
.
Access by calling const {MapTypeRegistry} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
MapTypeRegistry | MapTypeRegistry() Parameters: None The MapTypeRegistry holds the collection of custom map types available to the map for its use. The API consults this registry when providing the list of available map types within controls, for example. |
Methods | |
---|---|
set | set(id, mapType) Parameters:
Return Value: None Sets the registry to associate the passed string identifier with the passed MapType. |
Inherited: addListener , bindTo , get , notify , setValues , unbind , unbindAll |
MapRestriction interface
google.maps . MapRestriction
interface
A restriction that can be applied to the Map. The map's viewport will not exceed these restrictions.
Properties | |
---|---|
latLngBounds | Type: LatLngBounds | LatLngBoundsLiteral When set, a user can only pan and zoom inside the given bounds. Bounds can restrict both longitude and latitude, or can restrict latitude only. For latitude-only bounds use west and east longitudes of -180 and 180, respectively, for example, latLngBounds: {north: northLat, south: southLat, west: -180, east: 180} . |
strictBounds optional | Type: boolean optional Bounds can be made more restrictive by setting the strictBounds flag to true . This reduces how far a user can zoom out, ensuring that everything outside of the restricted bounds stays hidden. The default is false , meaning that a user can zoom out until the entire bounded area is in view, possibly including areas outside the bounded area. |
TrafficLayer class
google.maps . TrafficLayer
class
A traffic layer.
This class extends MVCObject
.
Access by calling const {TrafficLayer} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
TrafficLayer | TrafficLayer([opts]) Parameters:
A layer that displays current road traffic. |
Methods | |
---|---|
getMap | getMap() Parameters: None Return Value: Map Returns the map on which this layer is displayed. |
setMap | setMap(map) Parameters:
Return Value: None Renders the layer on the specified map. If map is set to null , the layer will be removed. |
setOptions | setOptions(options) Parameters:
Return Value: None |
Inherited: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
TrafficLayerOptions interface
google.maps . TrafficLayerOptions
interface
TrafficLayerOptions object used to define the properties that can be set on a TrafficLayer.
Properties | |
---|---|
autoRefresh optional | Type: boolean optional Default: true Whether the traffic layer refreshes with updated information automatically. |
map optional | Type: Map optional Map on which to display the traffic layer. |
TransitLayer class
google.maps . TransitLayer
class
A transit layer.
This class extends MVCObject
.
Access by calling const {TransitLayer} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
TransitLayer | TransitLayer() Parameters: None A layer that displays transit lines. |
Methods | |
---|---|
getMap | getMap() Parameters: None Return Value: Map Returns the map on which this layer is displayed. |
setMap | setMap(map) Parameters:
Return Value: None Renders the layer on the specified map. If map is set to null , the layer will be removed. |
Inherited: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
BicyclingLayer class
google.maps . BicyclingLayer
class
A layer showing bike lanes and paths.
This class extends MVCObject
.
Access by calling const {BicyclingLayer} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
BicyclingLayer | BicyclingLayer() Parameters: None A layer that displays bike lanes and paths and demotes large roads. |
Methods | |
---|---|
getMap | getMap() Parameters: None Return Value: Map Returns the map on which this layer is displayed. |
setMap | setMap(map) Parameters:
Return Value: None Renders the layer on the specified map. If map is set to null , the layer will be removed. |
Inherited: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
CameraOptions interface
google.maps . CameraOptions
interface
Used for setting the map's camera options.
Properties | |
---|---|
center optional | Type: LatLngLiteral | LatLng optional |
heading optional | Type: number optional |
tilt optional | Type: number optional |
zoom optional | Type: number optional |
VisibleRegion interface
google.maps . VisibleRegion
interface
Contains the four points defining the four-sided polygon that is the visible region of the map. On a vector map this polygon can be a trapezoid instead of a rectangle, when a vector map has tilt.
Properties | |
---|---|
farLeft | Type: LatLng |
farRight | Type: LatLng |
latLngBounds | Type: LatLngBounds The smallest bounding box that includes the visible region. |
nearLeft | Type: LatLng |
nearRight | Type: LatLng |
RenderingType constants
google.maps . RenderingType
constants
Access by calling const {RenderingType} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constants | |
---|---|
RASTER | Indicates that the map is a raster map. |
UNINITIALIZED | Indicates that it is unknown yet whether the map is vector or raster, because the map has not finished initializing yet. |
VECTOR | Indicates that the map is a vector map. |
MapCapabilities interface
google.maps . MapCapabilities
interface
Object containing a snapshot of what capabilities are currently available for the Map. Note that this does not necessarily mean that relevant modules are loaded or initialized, but rather that the current map has permission to use these APIs. See the properties for a list of possible capabilities.
Properties | |
---|---|
isAdvancedMarkersAvailable optional | Type: boolean optional If true, this map is configured properly to allow for the use of advanced markers. Note that you must still import the marker library in order to use advanced markers. See https://goo.gle/gmp-isAdvancedMarkersAvailable for more information. |
isDataDrivenStylingAvailable optional | Type: boolean optional If true, this map is configured properly to allow for the use of data-driven styling for at least one FeatureLayer. See https://goo.gle/gmp-data-driven-styling and https://goo.gle/gmp-FeatureLayerIsAvailable for more information. |
Map class
google.maps . Map
class
This class extends MVCObject
.
Access by calling const {Map} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
Map | Map(mapDiv[, opts]) Parameters:
Creates a new map inside of the given HTML container, which is typically a DIV element. |
Properties | |
---|---|
controls | Type: Array < MVCArray < HTMLElement >> Additional controls to attach to the map. To add a control to the map, add the control's <div> to the MVCArray corresponding to the ControlPosition where it should be rendered. |
data | Type: Data An instance of Data , bound to the map. Add features to this Data object to conveniently display them on this map. |
mapTypes | Type: MapTypeRegistry A registry of MapType instances by string ID. |
overlayMapTypes | Additional map types to overlay. Overlay map types will display on top of the base map they are attached to, in the order in which they appear in the overlayMapTypes array (overlays with higher index values are displayed in front of overlays with lower index values). |
Methods | |
---|---|
fitBounds | fitBounds(bounds[, padding]) Parameters:
Return Value: None Sets the viewport to contain the given bounds. Note: When the map is set to display: none , the fitBounds function reads the map's size as 0x0, and therefore does not do anything. To change the viewport while the map is hidden, set the map to visibility: hidden , thereby ensuring the map div has an actual size. For vector maps, this method sets the map's tilt and heading to their default zero values. Calling this method may cause a smooth animation as the map pans and zooms to fit the bounds. Whether or not this method animates depends on an internal heuristic. |
getBounds | getBounds() Parameters: None Return Value: LatLngBounds |undefined The lat/lng bounds of the current viewport. Returns the lat/lng bounds of the current viewport. If more than one copy of the world is visible, the bounds range in longitude from -180 to 180 degrees inclusive. If the map is not yet initialized or center and zoom have not been set then the result is undefined . For vector maps with non-zero tilt or heading, the returned lat/lng bounds represents the smallest bounding box that includes the visible region of the map's viewport. See MapCanvasProjection.getVisibleRegion for getting the exact visible region of the map's viewport. |
getCenter | getCenter() Parameters: None Return Value: LatLng |undefined |
getClickableIcons | getClickableIcons() Parameters: None Return Value: boolean|undefined Returns the clickability of the map icons. A map icon represents a point of interest, also known as a POI. If the returned value is true , then the icons are clickable on the map. |
getDatasetFeatureLayer | getDatasetFeatureLayer(datasetId) Parameters:
Return Value: FeatureLayer Returns the FeatureLayer for the specified datasetId . Dataset IDs must be configured in the Google Cloud Console. If the dataset ID is not associated with the map's map style, or if Data-driven styling is not available (no map ID, no vector tiles, no Data-Driven Styling feature layers or Datasets configured in the Map Style), this logs an error, and the resulting FeatureLayer.isAvailable will be false. |
getDiv | getDiv() Parameters: None Return Value: HTMLElement The mapDiv of the map. |
getFeatureLayer | getFeatureLayer(featureType) Parameters:
Return Value: FeatureLayer Returns the FeatureLayer of the specific FeatureType . A FeatureLayer must be enabled in the Google Cloud Console. If a FeatureLayer of the specified FeatureType does not exist on this map, or if Data-driven styling is not available (no map ID, no vector tiles, and no FeatureLayer enabled in the map style), this logs an error, and the resulting FeatureLayer.isAvailable will be false. |
getHeading | getHeading() Parameters: None Return Value: number|undefined Returns the compass heading of the map. The heading value is measured in degrees (clockwise) from cardinal direction North. If the map is not yet initialized then the result is undefined . |
getMapCapabilities | getMapCapabilities() Parameters: None Return Value: MapCapabilities Informs the caller of the current capabilities available to the map based on the Map ID that was provided. |
getMapTypeId | getMapTypeId() Parameters: None Return Value: MapTypeId |string|undefined |
getProjection | getProjection() Parameters: None Return Value: Projection |undefined Returns the current Projection . If the map is not yet initialized then the result is undefined . Listen to the projection_changed event and check its value to ensure it is not undefined . |
getRenderingType | getRenderingType() Parameters: None Return Value: RenderingType Returns the current RenderingType of the map. |
getStreetView | getStreetView() Parameters: None Return Value: StreetViewPanorama The panorama bound to the map. Returns the default StreetViewPanorama bound to the map, which may be a default panorama embedded within the map, or the panorama set using setStreetView() . Changes to the map's streetViewControl will be reflected in the display of such a bound panorama. |
getTilt | getTilt() Parameters: None Return Value: number|undefined Returns the current angle of incidence of the map, in degrees from the viewport plane to the map plane. For raster maps, the result will be 0 for imagery taken directly overhead or 45 for 45° imagery. This method does not return the value set by setTilt . See setTilt for details. |
getZoom | getZoom() Parameters: None Return Value: number|undefined Returns the zoom of the map. If the zoom has not been set then the result is undefined . |
moveCamera | moveCamera(cameraOptions) Parameters:
Return Value: None Immediately sets the map's camera to the target camera options, without animation. |
panBy | panBy(x, y) Parameters:
Return Value: None Changes the center of the map by the given distance in pixels. If the distance is less than both the width and height of the map, the transition will be smoothly animated. Note that the map coordinate system increases from west to east (for x values) and north to south (for y values). |
panTo | panTo(latLng) Parameters:
Return Value: None Changes the center of the map to the given LatLng . If the change is less than both the width and height of the map, the transition will be smoothly animated. |
panToBounds | panToBounds(latLngBounds[, padding]) Parameters:
Return Value: None Pans the map by the minimum amount necessary to contain the given LatLngBounds . It makes no guarantee where on the map the bounds will be, except that the map will be panned to show as much of the bounds as possible inside {currentMapSizeInPx} - {padding} . For both raster and vector maps, the map's zoom, tilt, and heading will not be changed. |
setCenter | setCenter(latlng) Parameters:
Return Value: None |
setClickableIcons | setClickableIcons(value) Parameters:
Return Value: None Controls whether the map icons are clickable or not. A map icon represents a point of interest, also known as a POI. To disable the clickability of map icons, pass a value of false to this method. |
setHeading | setHeading(heading) Parameters:
Return Value: None Sets the compass heading for map measured in degrees from cardinal direction North. For raster maps, this method only applies to aerial imagery. |
setMapTypeId | setMapTypeId(mapTypeId) Parameters:
Return Value: None |
setOptions | setOptions(options) Parameters:
Return Value: None |
setStreetView | setStreetView(panorama) Parameters:
Return Value: None Binds a StreetViewPanorama to the map. This panorama overrides the default StreetViewPanorama , allowing the map to bind to an external panorama outside of the map. Setting the panorama to null binds the default embedded panorama back to the map. |
setTilt | setTilt(tilt) Parameters:
Return Value: None For vector maps, sets the angle of incidence of the map. The allowed values are restricted depending on the zoom level of the map. For raster maps, controls the automatic switching behavior for the angle of incidence of the map. The only allowed values are 0 and 45 . setTilt(0) causes the map to always use a 0° overhead view regardless of the zoom level and viewport. setTilt(45) causes the tilt angle to automatically switch to 45 whenever 45° imagery is available for the current zoom level and viewport, and switch back to 0 whenever 45° imagery is not available (this is the default behavior). 45° imagery is only available for satellite and hybrid map types, within some locations, and at some zoom levels. Note: getTilt returns the current tilt angle, not the value set by setTilt . Because getTilt and setTilt refer to different things, do not bind() the tilt property; doing so may yield unpredictable effects. |
setZoom | setZoom(zoom) Parameters:
Return Value: None Sets the zoom of the map. |
Inherited: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
Constants | |
---|---|
DEMO_MAP_ID | Map ID which can be used for code samples which require a Map ID. This Map ID is not intended for use in production applications and cannot be used for features which require cloud configuration (such as Cloud Styling). |
События | |
---|---|
bounds_changed | function() Arguments: None This event is fired when the viewport bounds have changed. |
center_changed | function() Arguments: None This event is fired when the map center property changes. |
click | function(event) Arguments:
This event is fired when the user clicks on the map. A MapMouseEvent with properties for the clicked location is returned unless a place icon was clicked, in which case an IconMouseEvent with a place ID is returned. IconMouseEvent and MapMouseEvent are identical, except that IconMouseEvent has the place ID field. The event can always be treated as an MapMouseEvent when the place ID is not important. The click event is not fired if a marker or info window was clicked. |
contextmenu | function(event) Arguments:
This event is fired when the DOM contextmenu event is fired on the map container. |
dblclick | function(event) Arguments:
This event is fired when the user double-clicks on the map. Note that the click event will sometimes fire once and sometimes twice, right before this one. |
drag | function() Arguments: None This event is repeatedly fired while the user drags the map. |
dragend | function() Arguments: None This event is fired when the user stops dragging the map. |
dragstart | function() Arguments: None This event is fired when the user starts dragging the map. |
heading_changed | function() Arguments: None This event is fired when the map heading property changes. |
idle | function() Arguments: None This event is fired when the map becomes idle after panning or zooming. |
isfractionalzoomenabled_changed | function() Arguments: None This event is fired when the isFractionalZoomEnabled property has changed. |
mapcapabilities_changed | function() Arguments: None This event is fired when the map capabilities change. |
maptypeid_changed | function() Arguments: None This event is fired when the mapTypeId property changes. |
mousemove | function(event) Arguments:
This event is fired whenever the user's mouse moves over the map container. |
mouseout | function(event) Arguments:
This event is fired when the user's mouse exits the map container. |
mouseover | function(event) Arguments:
This event is fired when the user's mouse enters the map container. |
projection_changed | function() Arguments: None This event is fired when the projection has changed. |
renderingtype_changed | function() Arguments: None This event is fired when the renderingType has changed. |
tilesloaded | function() Arguments: None This event is fired when the visible tiles have finished loading. |
tilt_changed | function() Arguments: None This event is fired when the map tilt property changes. |
zoom_changed | function() Arguments: None This event is fired when the map zoom property changes. |
| function(event) Arguments:
This event is fired when the user right-clicks on the map. |
MapOptions interface
google.maps . MapOptions
interface
MapOptions object used to define the properties that can be set on a Map.
Properties | |
---|---|
backgroundColor optional | Type: string optional Color used for the background of the Map div. This color will be visible when tiles have not yet loaded as the user pans. This option can only be set when the map is initialized. |
center optional | Type: LatLng | LatLngLiteral optional The initial Map center. |
clickableIcons optional | Type: boolean optional Default: true When false , map icons are not clickable. A map icon represents a point of interest, also known as a POI. |
controlSize optional | Type: number optional Size in pixels of the controls appearing on the map. This value must be supplied directly when creating the Map, updating this value later may bring the controls into an undefined state. Only governs the controls made by the Maps API itself. Does not scale developer created custom controls. |
disableDefaultUI optional | Type: boolean optional Enables/disables all default UI buttons. May be overridden individually. Does not disable the keyboard controls, which are separately controlled by the MapOptions.keyboardShortcuts option. Does not disable gesture controls, which are separately controlled by the MapOptions.gestureHandling option. |
disableDoubleClickZoom optional | Type: boolean optional Enables/disables zoom and center on double click. Enabled by default. Note : This property is not recommended . To disable zooming on double click, you can use the |
| Type: boolean optional If false , prevents the map from being dragged. Dragging is enabled by default. |
draggableCursor optional | Type: string optional The name or url of the cursor to display when mousing over a draggable map. This property uses the css cursor attribute to change the icon. As with the css property, you must specify at least one fallback cursor that is not a URL. For example: draggableCursor: 'url( http://www.example.com/icon.png ), auto;' . |
draggingCursor optional | Type: string optional The name or url of the cursor to display when the map is being dragged. This property uses the css cursor attribute to change the icon. As with the css property, you must specify at least one fallback cursor that is not a URL. For example: draggingCursor: 'url( http://www.example.com/icon.png ), auto;' . |
fullscreenControl optional | Type: boolean optional The enabled/disabled state of the Fullscreen control. |
fullscreenControlOptions optional | Type: FullscreenControlOptions optional The display options for the Fullscreen control. |
gestureHandling optional | Type: string optional This setting controls how the API handles gestures on the map. Allowed values:
|
heading optional | Type: number optional The heading for aerial imagery in degrees measured clockwise from cardinal direction North. Headings are snapped to the nearest available angle for which imagery is available. |
isFractionalZoomEnabled optional | Type: boolean optional Default: true for vector maps and false for raster maps Whether the map should allow fractional zoom levels. Listen to isfractionalzoomenabled_changed to know when the default has been set. |
keyboardShortcuts optional | Type: boolean optional If false , prevents the map from being controlled by the keyboard. Keyboard shortcuts are enabled by default. |
mapId optional | Type: string optional The Map ID of the map. This parameter cannot be set or changed after a map is instantiated. |
mapTypeControl optional | Type: boolean optional The initial enabled/disabled state of the Map type control. |
mapTypeControlOptions optional | Type: MapTypeControlOptions optional The initial display options for the Map type control. |
mapTypeId optional | Type: MapTypeId |string optional The initial Map mapTypeId. Defaults to ROADMAP . |
maxZoom optional | Type: number optional The maximum zoom level which will be displayed on the map. If omitted, or set to null , 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 . |
minZoom optional | Type: number optional The minimum zoom level which will be displayed on the map. If omitted, or set to null , 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 . |
noClear optional | Type: boolean optional If true , do not clear the contents of the Map div. |
panControl optional | Type: boolean optional The enabled/disabled state of the Pan control. Note: The Pan control is not available in the new set of controls introduced in v3.22 of the Google Maps JavaScript API. While using v3.22 and v3.23, you can choose to use the earlier set of controls rather than the new controls, thus making the Pan control available as part of the old control set. See What's New in the v3.22 Map Controls . |
panControlOptions optional | Type: PanControlOptions optional The display options for the Pan control. Note: The Pan control is not available in the new set of controls introduced in v3.22 of the Google Maps JavaScript API. While using v3.22 and v3.23, you can choose to use the earlier set of controls rather than the new controls, thus making the Pan control available as part of the old control set. See What's New in the v3.22 Map Controls . |
restriction optional | Type: MapRestriction optional Defines a boundary that restricts the area of the map accessible to users. When set, a user can only pan and zoom while the camera view stays inside the limits of the boundary. |
rotateControl optional | Type: boolean optional The enabled/disabled state of the Rotate control. |
rotateControlOptions optional | Type: RotateControlOptions optional The display options for the Rotate control. |
scaleControl optional | Type: boolean optional The initial enabled/disabled state of the Scale control. |
scaleControlOptions optional | Type: ScaleControlOptions optional The initial display options for the Scale control. |
scrollwheel optional | Type: boolean optional If false , disables zooming on the map using a mouse scroll wheel. The scrollwheel is enabled by default. Note : This property is not recommended . To disable zooming using scrollwheel, you can use the |
streetView optional | Type: StreetViewPanorama optional A StreetViewPanorama to display when the Street View pegman is dropped on the map. If no panorama is specified, a default StreetViewPanorama will be displayed in the map's div when the pegman is dropped. |
streetViewControl optional | Type: boolean optional The initial enabled/disabled state of the Street View Pegman control. This control is part of the default UI, and should be set to false when displaying a map type on which the Street View road overlay should not appear (eg a non-Earth map type). |
streetViewControlOptions optional | Type: StreetViewControlOptions optional The initial display options for the Street View Pegman control. |
styles optional | Type: Array < MapTypeStyle > optional Styles to apply to each of the default map types. Note that for satellite / hybrid and terrain modes, these styles will only apply to labels and geometry. |
tilt optional | Type: number optional For vector maps, sets the angle of incidence of the map. The allowed values are restricted depending on the zoom level of the map. For raster maps, controls the automatic switching behavior for the angle of incidence of the map. The only allowed values are 0 and 45 . The value 0 causes the map to always use a 0° overhead view regardless of the zoom level and viewport. The value 45 causes the tilt angle to automatically switch to 45 whenever 45° imagery is available for the current zoom level and viewport, and switch back to 0 whenever 45° imagery is not available (this is the default behavior). 45° imagery is only available for satellite and hybrid map types, within some locations, and at some zoom levels. Note: getTilt returns the current tilt angle, not the value specified by this option. Because getTilt and this option refer to different things, do not bind() the tilt property; doing so may yield unpredictable effects. |
zoom optional | Type: number optional The initial Map zoom level. Valid zoom values are numbers from zero up to the supported maximum zoom level . Larger zoom values correspond to a higher resolution. |
zoomControl optional | Type: boolean optional The enabled/disabled state of the Zoom control. |
zoomControlOptions optional | Type: ZoomControlOptions optional The display options for the Zoom control. |
MapElement class
google.maps . MapElement
class
MapElement is an HTMLElement
subclass for rendering maps. After loading the maps
library, a map can be created in HTML. Например:
<gmp-map center="37.4220656,-122.0840897" zoom="10" map-id="DEMO_MAP_ID"></gmp-map>
Internally, it uses Map
, which can be accessed with the innerMap
property.
Custom element:
<gmp-map center="lat,lng" map-id="string" zoom="number"></gmp-map>
This class extends HTMLElement
.
This class implements MapElementOptions
.
Access by calling const {MapElement} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Properties | |
---|---|
center | Type: LatLng | LatLngLiteral optional HTML attribute:
|
innerMap | Type: Map A reference to the Map that the MapElement uses internally. |
mapId | Type: string optional HTML attribute:
|
zoom | Type: number optional HTML attribute:
|
Methods | |
---|---|
addEventListener | addEventListener(type, listener[, options]) Parameters:
Return Value: void Sets up a function that will be called whenever the specified event is delivered to the target. See addEventListener |
removeEventListener | removeEventListener(type, listener[, options]) Parameters:
Return Value: void Removes an event listener previously registered with addEventListener from the target. See removeEventListener |
MapElementOptions interface
google.maps . MapElementOptions
interface
MapElementOptions object used to define the properties that can be set on a MapElement.
Properties | |
---|---|
center optional | Type: LatLng | LatLngLiteral optional The initial Map center. |
mapId optional | Type: string optional The Map ID of the map. This parameter cannot be set or changed after a map is instantiated. |
zoom optional | Type: number optional The initial Map zoom level. Valid zoom values are numbers from zero up to the supported maximum zoom level . Larger zoom values correspond to a higher resolution. |
MapTypeStyle interface
google.maps . MapTypeStyle
interface
The MapTypeStyle
is a collection of selectors and stylers that define how the map should be styled. Selectors specify the map features and/or elements that should be affected, and stylers specify how those features and elements should be modified. For details, see the style reference .
Properties | |
---|---|
stylers | The style rules to apply to the selected map features and elements. The rules are applied in the order that you specify in this array. For guidelines on usage and allowed values, see the style reference . |
elementType optional | Type: string optional The element to which a styler should be applied. An element is a visual aspect of a feature on the map. Example: a label, an icon, the stroke or fill applied to the geometry, and more. Optional. If elementType is not specified, the value is assumed to be 'all' . For details of usage and allowed values, see the style reference . |
featureType optional | Type: string optional The feature, or group of features, to which a styler should be applied. Optional. If featureType is not specified, the value is assumed to be 'all' . For details of usage and allowed values, see the style reference . |
MapMouseEvent interface
google.maps . MapMouseEvent
interface
This object is returned from various mouse events on the map and overlays, and contains all the fields shown below.
Properties | |
---|---|
domEvent | Type: MouseEvent | TouchEvent | PointerEvent | KeyboardEvent | Event The corresponding native DOM event. Developers should not rely on target , currentTarget , relatedTarget and path properties being defined and consistent. Developers should not also rely on the DOM structure of the internal implementation of the Maps API. Due to internal event mapping, the domEvent may have different semantics from the MapMouseEvent (eg a MapMouseEvent "click" may have a domEvent of type KeyboardEvent ). |
latLng optional | Type: LatLng optional The latitude/longitude that was below the cursor when the event occurred. |
Methods | |
---|---|
stop | stop() Parameters: None Return Value: void Prevents this event from propagating further. |
IconMouseEvent interface
google.maps . IconMouseEvent
interface
This object is sent in an event when a user clicks on an icon on the map. The place ID of this place is stored in the placeId member. To prevent the default info window from showing up, call the stop() method on this event to prevent it being propagated. Learn more about place IDs in the Places API developer guide.
This interface extends MapMouseEvent
.
Properties | |
---|---|
placeId optional | Type: string optional The place ID of the place that was clicked. This place ID can be used to query more information about the feature that was clicked. Learn more about place IDs in the Places API developer guide. |
Inherited: domEvent , latLng |
Methods | |
---|---|
Inherited: stop |
MapTypeId constants
google.maps . MapTypeId
constants
Identifiers for common MapTypes. Specify these by value, or by using the constant's name. For example, 'satellite'
or google.maps.MapTypeId.SATELLITE
.
Access by calling const {MapTypeId} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constants | |
---|---|
HYBRID | This map type displays a transparent layer of major streets on satellite images. |
ROADMAP | This map type displays a normal street map. |
SATELLITE | This map type displays satellite images. |
TERRAIN | This map type displays maps with physical features such as terrain and vegetation. |
MapTypeRegistry class
google.maps . MapTypeRegistry
class
A registry for MapType instances, keyed by MapType id.
This class extends MVCObject
.
Access by calling const {MapTypeRegistry} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
MapTypeRegistry | MapTypeRegistry() Parameters: None The MapTypeRegistry holds the collection of custom map types available to the map for its use. The API consults this registry when providing the list of available map types within controls, for example. |
Methods | |
---|---|
set | set(id, mapType) Parameters:
Return Value: None Sets the registry to associate the passed string identifier with the passed MapType. |
Inherited: addListener , bindTo , get , notify , setValues , unbind , unbindAll |
MapRestriction interface
google.maps . MapRestriction
interface
A restriction that can be applied to the Map. The map's viewport will not exceed these restrictions.
Properties | |
---|---|
latLngBounds | Type: LatLngBounds | LatLngBoundsLiteral When set, a user can only pan and zoom inside the given bounds. Bounds can restrict both longitude and latitude, or can restrict latitude only. For latitude-only bounds use west and east longitudes of -180 and 180, respectively, for example, latLngBounds: {north: northLat, south: southLat, west: -180, east: 180} . |
strictBounds optional | Type: boolean optional Bounds can be made more restrictive by setting the strictBounds flag to true . This reduces how far a user can zoom out, ensuring that everything outside of the restricted bounds stays hidden. The default is false , meaning that a user can zoom out until the entire bounded area is in view, possibly including areas outside the bounded area. |
TrafficLayer class
google.maps . TrafficLayer
class
A traffic layer.
This class extends MVCObject
.
Access by calling const {TrafficLayer} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
TrafficLayer | TrafficLayer([opts]) Parameters:
A layer that displays current road traffic. |
Methods | |
---|---|
getMap | getMap() Parameters: None Return Value: Map Returns the map on which this layer is displayed. |
setMap | setMap(map) Parameters:
Return Value: None Renders the layer on the specified map. If map is set to null , the layer will be removed. |
setOptions | setOptions(options) Parameters:
Return Value: None |
Inherited: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
TrafficLayerOptions interface
google.maps . TrafficLayerOptions
interface
TrafficLayerOptions object used to define the properties that can be set on a TrafficLayer.
Properties | |
---|---|
autoRefresh optional | Type: boolean optional Default: true Whether the traffic layer refreshes with updated information automatically. |
map optional | Type: Map optional Map on which to display the traffic layer. |
TransitLayer class
google.maps . TransitLayer
class
A transit layer.
This class extends MVCObject
.
Access by calling const {TransitLayer} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
TransitLayer | TransitLayer() Parameters: None A layer that displays transit lines. |
Methods | |
---|---|
getMap | getMap() Parameters: None Return Value: Map Returns the map on which this layer is displayed. |
setMap | setMap(map) Parameters:
Return Value: None Renders the layer on the specified map. If map is set to null , the layer will be removed. |
Inherited: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
BicyclingLayer class
google.maps . BicyclingLayer
class
A layer showing bike lanes and paths.
This class extends MVCObject
.
Access by calling const {BicyclingLayer} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
BicyclingLayer | BicyclingLayer() Parameters: None A layer that displays bike lanes and paths and demotes large roads. |
Methods | |
---|---|
getMap | getMap() Parameters: None Return Value: Map Returns the map on which this layer is displayed. |
setMap | setMap(map) Parameters:
Return Value: None Renders the layer on the specified map. If map is set to null , the layer will be removed. |
Inherited: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
CameraOptions interface
google.maps . CameraOptions
interface
Used for setting the map's camera options.
Properties | |
---|---|
center optional | Type: LatLngLiteral | LatLng optional |
heading optional | Type: number optional |
tilt optional | Type: number optional |
zoom optional | Type: number optional |
VisibleRegion interface
google.maps . VisibleRegion
interface
Contains the four points defining the four-sided polygon that is the visible region of the map. On a vector map this polygon can be a trapezoid instead of a rectangle, when a vector map has tilt.
Properties | |
---|---|
farLeft | Type: LatLng |
farRight | Type: LatLng |
latLngBounds | Type: LatLngBounds The smallest bounding box that includes the visible region. |
nearLeft | Type: LatLng |
nearRight | Type: LatLng |
RenderingType constants
google.maps . RenderingType
constants
Access by calling const {RenderingType} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constants | |
---|---|
RASTER | Indicates that the map is a raster map. |
UNINITIALIZED | Indicates that it is unknown yet whether the map is vector or raster, because the map has not finished initializing yet. |
VECTOR | Indicates that the map is a vector map. |
MapCapabilities interface
google.maps . MapCapabilities
interface
Object containing a snapshot of what capabilities are currently available for the Map. Note that this does not necessarily mean that relevant modules are loaded or initialized, but rather that the current map has permission to use these APIs. See the properties for a list of possible capabilities.
Properties | |
---|---|
isAdvancedMarkersAvailable optional | Type: boolean optional If true, this map is configured properly to allow for the use of advanced markers. Note that you must still import the marker library in order to use advanced markers. See https://goo.gle/gmp-isAdvancedMarkersAvailable for more information. |
isDataDrivenStylingAvailable optional | Type: boolean optional If true, this map is configured properly to allow for the use of data-driven styling for at least one FeatureLayer. See https://goo.gle/gmp-data-driven-styling and https://goo.gle/gmp-FeatureLayerIsAvailable for more information. |
Map class
google.maps . Map
class
This class extends MVCObject
.
Access by calling const {Map} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
Map | Map(mapDiv[, opts]) Parameters:
Creates a new map inside of the given HTML container, which is typically a DIV element. |
Properties | |
---|---|
controls | Type: Array < MVCArray < HTMLElement >> Additional controls to attach to the map. To add a control to the map, add the control's <div> to the MVCArray corresponding to the ControlPosition where it should be rendered. |
data | Type: Data An instance of Data , bound to the map. Add features to this Data object to conveniently display them on this map. |
mapTypes | Type: MapTypeRegistry A registry of MapType instances by string ID. |
overlayMapTypes | Additional map types to overlay. Overlay map types will display on top of the base map they are attached to, in the order in which they appear in the overlayMapTypes array (overlays with higher index values are displayed in front of overlays with lower index values). |
Methods | |
---|---|
fitBounds | fitBounds(bounds[, padding]) Parameters:
Return Value: None Sets the viewport to contain the given bounds. Note: When the map is set to display: none , the fitBounds function reads the map's size as 0x0, and therefore does not do anything. To change the viewport while the map is hidden, set the map to visibility: hidden , thereby ensuring the map div has an actual size. For vector maps, this method sets the map's tilt and heading to their default zero values. Calling this method may cause a smooth animation as the map pans and zooms to fit the bounds. Whether or not this method animates depends on an internal heuristic. |
getBounds | getBounds() Parameters: None Return Value: LatLngBounds |undefined The lat/lng bounds of the current viewport. Returns the lat/lng bounds of the current viewport. If more than one copy of the world is visible, the bounds range in longitude from -180 to 180 degrees inclusive. If the map is not yet initialized or center and zoom have not been set then the result is undefined . For vector maps with non-zero tilt or heading, the returned lat/lng bounds represents the smallest bounding box that includes the visible region of the map's viewport. See MapCanvasProjection.getVisibleRegion for getting the exact visible region of the map's viewport. |
getCenter | getCenter() Parameters: None Return Value: LatLng |undefined |
getClickableIcons | getClickableIcons() Parameters: None Return Value: boolean|undefined Returns the clickability of the map icons. A map icon represents a point of interest, also known as a POI. If the returned value is true , then the icons are clickable on the map. |
getDatasetFeatureLayer | getDatasetFeatureLayer(datasetId) Parameters:
Return Value: FeatureLayer Returns the FeatureLayer for the specified datasetId . Dataset IDs must be configured in the Google Cloud Console. If the dataset ID is not associated with the map's map style, or if Data-driven styling is not available (no map ID, no vector tiles, no Data-Driven Styling feature layers or Datasets configured in the Map Style), this logs an error, and the resulting FeatureLayer.isAvailable will be false. |
getDiv | getDiv() Parameters: None Return Value: HTMLElement The mapDiv of the map. |
getFeatureLayer | getFeatureLayer(featureType) Parameters:
Return Value: FeatureLayer Returns the FeatureLayer of the specific FeatureType . A FeatureLayer must be enabled in the Google Cloud Console. If a FeatureLayer of the specified FeatureType does not exist on this map, or if Data-driven styling is not available (no map ID, no vector tiles, and no FeatureLayer enabled in the map style), this logs an error, and the resulting FeatureLayer.isAvailable will be false. |
getHeading | getHeading() Parameters: None Return Value: number|undefined Returns the compass heading of the map. The heading value is measured in degrees (clockwise) from cardinal direction North. If the map is not yet initialized then the result is undefined . |
getMapCapabilities | getMapCapabilities() Parameters: None Return Value: MapCapabilities Informs the caller of the current capabilities available to the map based on the Map ID that was provided. |
getMapTypeId | getMapTypeId() Parameters: None Return Value: MapTypeId |string|undefined |
getProjection | getProjection() Parameters: None Return Value: Projection |undefined Returns the current Projection . If the map is not yet initialized then the result is undefined . Listen to the projection_changed event and check its value to ensure it is not undefined . |
getRenderingType | getRenderingType() Parameters: None Return Value: RenderingType Returns the current RenderingType of the map. |
getStreetView | getStreetView() Parameters: None Return Value: StreetViewPanorama The panorama bound to the map. Returns the default StreetViewPanorama bound to the map, which may be a default panorama embedded within the map, or the panorama set using setStreetView() . Changes to the map's streetViewControl will be reflected in the display of such a bound panorama. |
getTilt | getTilt() Parameters: None Return Value: number|undefined Returns the current angle of incidence of the map, in degrees from the viewport plane to the map plane. For raster maps, the result will be 0 for imagery taken directly overhead or 45 for 45° imagery. This method does not return the value set by setTilt . See setTilt for details. |
getZoom | getZoom() Parameters: None Return Value: number|undefined Returns the zoom of the map. If the zoom has not been set then the result is undefined . |
moveCamera | moveCamera(cameraOptions) Parameters:
Return Value: None Immediately sets the map's camera to the target camera options, without animation. |
panBy | panBy(x, y) Parameters:
Return Value: None Changes the center of the map by the given distance in pixels. If the distance is less than both the width and height of the map, the transition will be smoothly animated. Note that the map coordinate system increases from west to east (for x values) and north to south (for y values). |
panTo | panTo(latLng) Parameters:
Return Value: None Changes the center of the map to the given LatLng . If the change is less than both the width and height of the map, the transition will be smoothly animated. |
panToBounds | panToBounds(latLngBounds[, padding]) Parameters:
Return Value: None Pans the map by the minimum amount necessary to contain the given LatLngBounds . It makes no guarantee where on the map the bounds will be, except that the map will be panned to show as much of the bounds as possible inside {currentMapSizeInPx} - {padding} . For both raster and vector maps, the map's zoom, tilt, and heading will not be changed. |
setCenter | setCenter(latlng) Parameters:
Return Value: None |
setClickableIcons | setClickableIcons(value) Parameters:
Return Value: None Controls whether the map icons are clickable or not. A map icon represents a point of interest, also known as a POI. To disable the clickability of map icons, pass a value of false to this method. |
setHeading | setHeading(heading) Parameters:
Return Value: None Sets the compass heading for map measured in degrees from cardinal direction North. For raster maps, this method only applies to aerial imagery. |
setMapTypeId | setMapTypeId(mapTypeId) Parameters:
Return Value: None |
setOptions | setOptions(options) Parameters:
Return Value: None |
setStreetView | setStreetView(panorama) Parameters:
Return Value: None Binds a StreetViewPanorama to the map. This panorama overrides the default StreetViewPanorama , allowing the map to bind to an external panorama outside of the map. Setting the panorama to null binds the default embedded panorama back to the map. |
setTilt | setTilt(tilt) Parameters:
Return Value: None For vector maps, sets the angle of incidence of the map. The allowed values are restricted depending on the zoom level of the map. For raster maps, controls the automatic switching behavior for the angle of incidence of the map. The only allowed values are 0 and 45 . setTilt(0) causes the map to always use a 0° overhead view regardless of the zoom level and viewport. setTilt(45) causes the tilt angle to automatically switch to 45 whenever 45° imagery is available for the current zoom level and viewport, and switch back to 0 whenever 45° imagery is not available (this is the default behavior). 45° imagery is only available for satellite and hybrid map types, within some locations, and at some zoom levels. Note: getTilt returns the current tilt angle, not the value set by setTilt . Because getTilt and setTilt refer to different things, do not bind() the tilt property; doing so may yield unpredictable effects. |
setZoom | setZoom(zoom) Parameters:
Return Value: None Sets the zoom of the map. |
Inherited: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
Constants | |
---|---|
DEMO_MAP_ID | Map ID which can be used for code samples which require a Map ID. This Map ID is not intended for use in production applications and cannot be used for features which require cloud configuration (such as Cloud Styling). |
События | |
---|---|
bounds_changed | function() Arguments: None This event is fired when the viewport bounds have changed. |
center_changed | function() Arguments: None This event is fired when the map center property changes. |
click | function(event) Arguments:
This event is fired when the user clicks on the map. A MapMouseEvent with properties for the clicked location is returned unless a place icon was clicked, in which case an IconMouseEvent with a place ID is returned. IconMouseEvent and MapMouseEvent are identical, except that IconMouseEvent has the place ID field. The event can always be treated as an MapMouseEvent when the place ID is not important. The click event is not fired if a marker or info window was clicked. |
contextmenu | function(event) Arguments:
This event is fired when the DOM contextmenu event is fired on the map container. |
dblclick | function(event) Arguments:
This event is fired when the user double-clicks on the map. Note that the click event will sometimes fire once and sometimes twice, right before this one. |
drag | function() Arguments: None This event is repeatedly fired while the user drags the map. |
dragend | function() Arguments: None This event is fired when the user stops dragging the map. |
dragstart | function() Arguments: None This event is fired when the user starts dragging the map. |
heading_changed | function() Arguments: None This event is fired when the map heading property changes. |
idle | function() Arguments: None This event is fired when the map becomes idle after panning or zooming. |
isfractionalzoomenabled_changed | function() Arguments: None This event is fired when the isFractionalZoomEnabled property has changed. |
mapcapabilities_changed | function() Arguments: None This event is fired when the map capabilities change. |
maptypeid_changed | function() Arguments: None This event is fired when the mapTypeId property changes. |
mousemove | function(event) Arguments:
This event is fired whenever the user's mouse moves over the map container. |
mouseout | function(event) Arguments:
This event is fired when the user's mouse exits the map container. |
mouseover | function(event) Arguments:
This event is fired when the user's mouse enters the map container. |
projection_changed | function() Arguments: None This event is fired when the projection has changed. |
renderingtype_changed | function() Arguments: None This event is fired when the renderingType has changed. |
tilesloaded | function() Arguments: None This event is fired when the visible tiles have finished loading. |
tilt_changed | function() Arguments: None This event is fired when the map tilt property changes. |
zoom_changed | function() Arguments: None This event is fired when the map zoom property changes. |
| function(event) Arguments:
This event is fired when the user right-clicks on the map. |
MapOptions interface
google.maps . MapOptions
interface
MapOptions object used to define the properties that can be set on a Map.
Properties | |
---|---|
backgroundColor optional | Type: string optional Color used for the background of the Map div. This color will be visible when tiles have not yet loaded as the user pans. This option can only be set when the map is initialized. |
center optional | Type: LatLng | LatLngLiteral optional The initial Map center. |
clickableIcons optional | Type: boolean optional Default: true When false , map icons are not clickable. A map icon represents a point of interest, also known as a POI. |
controlSize optional | Type: number optional Size in pixels of the controls appearing on the map. This value must be supplied directly when creating the Map, updating this value later may bring the controls into an undefined state. Only governs the controls made by the Maps API itself. Does not scale developer created custom controls. |
disableDefaultUI optional | Type: boolean optional Enables/disables all default UI buttons. May be overridden individually. Does not disable the keyboard controls, which are separately controlled by the MapOptions.keyboardShortcuts option. Does not disable gesture controls, which are separately controlled by the MapOptions.gestureHandling option. |
disableDoubleClickZoom optional | Type: boolean optional Enables/disables zoom and center on double click. Enabled by default. Note : This property is not recommended . To disable zooming on double click, you can use the |
| Type: boolean optional If false , prevents the map from being dragged. Dragging is enabled by default. |
draggableCursor optional | Type: string optional The name or url of the cursor to display when mousing over a draggable map. This property uses the css cursor attribute to change the icon. As with the css property, you must specify at least one fallback cursor that is not a URL. For example: draggableCursor: 'url( http://www.example.com/icon.png ), auto;' . |
draggingCursor optional | Type: string optional The name or url of the cursor to display when the map is being dragged. This property uses the css cursor attribute to change the icon. As with the css property, you must specify at least one fallback cursor that is not a URL. For example: draggingCursor: 'url( http://www.example.com/icon.png ), auto;' . |
fullscreenControl optional | Type: boolean optional The enabled/disabled state of the Fullscreen control. |
fullscreenControlOptions optional | Type: FullscreenControlOptions optional The display options for the Fullscreen control. |
gestureHandling optional | Type: string optional This setting controls how the API handles gestures on the map. Allowed values:
|
heading optional | Type: number optional The heading for aerial imagery in degrees measured clockwise from cardinal direction North. Headings are snapped to the nearest available angle for which imagery is available. |
isFractionalZoomEnabled optional | Type: boolean optional Default: true for vector maps and false for raster maps Whether the map should allow fractional zoom levels. Listen to isfractionalzoomenabled_changed to know when the default has been set. |
keyboardShortcuts optional | Type: boolean optional If false , prevents the map from being controlled by the keyboard. Keyboard shortcuts are enabled by default. |
mapId optional | Type: string optional The Map ID of the map. This parameter cannot be set or changed after a map is instantiated. |
mapTypeControl optional | Type: boolean optional The initial enabled/disabled state of the Map type control. |
mapTypeControlOptions optional | Type: MapTypeControlOptions optional The initial display options for the Map type control. |
mapTypeId optional | Type: MapTypeId |string optional The initial Map mapTypeId. Defaults to ROADMAP . |
maxZoom optional | Type: number optional The maximum zoom level which will be displayed on the map. If omitted, or set to null , 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 . |
minZoom optional | Type: number optional The minimum zoom level which will be displayed on the map. If omitted, or set to null , 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 . |
noClear optional | Type: boolean optional If true , do not clear the contents of the Map div. |
panControl optional | Type: boolean optional The enabled/disabled state of the Pan control. Note: The Pan control is not available in the new set of controls introduced in v3.22 of the Google Maps JavaScript API. While using v3.22 and v3.23, you can choose to use the earlier set of controls rather than the new controls, thus making the Pan control available as part of the old control set. See What's New in the v3.22 Map Controls . |
panControlOptions optional | Type: PanControlOptions optional The display options for the Pan control. Note: The Pan control is not available in the new set of controls introduced in v3.22 of the Google Maps JavaScript API. While using v3.22 and v3.23, you can choose to use the earlier set of controls rather than the new controls, thus making the Pan control available as part of the old control set. See What's New in the v3.22 Map Controls . |
restriction optional | Type: MapRestriction optional Defines a boundary that restricts the area of the map accessible to users. When set, a user can only pan and zoom while the camera view stays inside the limits of the boundary. |
rotateControl optional | Type: boolean optional The enabled/disabled state of the Rotate control. |
rotateControlOptions optional | Type: RotateControlOptions optional The display options for the Rotate control. |
scaleControl optional | Type: boolean optional The initial enabled/disabled state of the Scale control. |
scaleControlOptions optional | Type: ScaleControlOptions optional The initial display options for the Scale control. |
scrollwheel optional | Type: boolean optional If false , disables zooming on the map using a mouse scroll wheel. The scrollwheel is enabled by default. Note : This property is not recommended . To disable zooming using scrollwheel, you can use the |
streetView optional | Type: StreetViewPanorama optional A StreetViewPanorama to display when the Street View pegman is dropped on the map. If no panorama is specified, a default StreetViewPanorama will be displayed in the map's div when the pegman is dropped. |
streetViewControl optional | Type: boolean optional The initial enabled/disabled state of the Street View Pegman control. This control is part of the default UI, and should be set to false when displaying a map type on which the Street View road overlay should not appear (eg a non-Earth map type). |
streetViewControlOptions optional | Type: StreetViewControlOptions optional The initial display options for the Street View Pegman control. |
styles optional | Type: Array < MapTypeStyle > optional Styles to apply to each of the default map types. Note that for satellite / hybrid and terrain modes, these styles will only apply to labels and geometry. |
tilt optional | Type: number optional For vector maps, sets the angle of incidence of the map. The allowed values are restricted depending on the zoom level of the map. For raster maps, controls the automatic switching behavior for the angle of incidence of the map. The only allowed values are 0 and 45 . The value 0 causes the map to always use a 0° overhead view regardless of the zoom level and viewport. The value 45 causes the tilt angle to automatically switch to 45 whenever 45° imagery is available for the current zoom level and viewport, and switch back to 0 whenever 45° imagery is not available (this is the default behavior). 45° imagery is only available for satellite and hybrid map types, within some locations, and at some zoom levels. Note: getTilt returns the current tilt angle, not the value specified by this option. Because getTilt and this option refer to different things, do not bind() the tilt property; doing so may yield unpredictable effects. |
zoom optional | Type: number optional The initial Map zoom level. Valid zoom values are numbers from zero up to the supported maximum zoom level . Larger zoom values correspond to a higher resolution. |
zoomControl optional | Type: boolean optional The enabled/disabled state of the Zoom control. |
zoomControlOptions optional | Type: ZoomControlOptions optional The display options for the Zoom control. |
MapElement class
google.maps . MapElement
class
MapElement is an HTMLElement
subclass for rendering maps. After loading the maps
library, a map can be created in HTML. Например:
<gmp-map center="37.4220656,-122.0840897" zoom="10" map-id="DEMO_MAP_ID"></gmp-map>
Internally, it uses Map
, which can be accessed with the innerMap
property.
Custom element:
<gmp-map center="lat,lng" map-id="string" zoom="number"></gmp-map>
This class extends HTMLElement
.
This class implements MapElementOptions
.
Access by calling const {MapElement} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Properties | |
---|---|
center | Type: LatLng | LatLngLiteral optional HTML attribute:
|
innerMap | Type: Map A reference to the Map that the MapElement uses internally. |
mapId | Type: string optional HTML attribute:
|
zoom | Type: number optional HTML attribute:
|
Methods | |
---|---|
addEventListener | addEventListener(type, listener[, options]) Parameters:
Return Value: void Sets up a function that will be called whenever the specified event is delivered to the target. See addEventListener |
removeEventListener | removeEventListener(type, listener[, options]) Parameters:
Return Value: void Removes an event listener previously registered with addEventListener from the target. See removeEventListener |
MapElementOptions interface
google.maps . MapElementOptions
interface
MapElementOptions object used to define the properties that can be set on a MapElement.
Properties | |
---|---|
center optional | Type: LatLng | LatLngLiteral optional The initial Map center. |
mapId optional | Type: string optional The Map ID of the map. This parameter cannot be set or changed after a map is instantiated. |
zoom optional | Type: number optional The initial Map zoom level. Valid zoom values are numbers from zero up to the supported maximum zoom level . Larger zoom values correspond to a higher resolution. |
MapTypeStyle interface
google.maps . MapTypeStyle
interface
The MapTypeStyle
is a collection of selectors and stylers that define how the map should be styled. Selectors specify the map features and/or elements that should be affected, and stylers specify how those features and elements should be modified. For details, see the style reference .
Properties | |
---|---|
stylers | The style rules to apply to the selected map features and elements. The rules are applied in the order that you specify in this array. For guidelines on usage and allowed values, see the style reference . |
elementType optional | Type: string optional The element to which a styler should be applied. An element is a visual aspect of a feature on the map. Example: a label, an icon, the stroke or fill applied to the geometry, and more. Optional. If elementType is not specified, the value is assumed to be 'all' . For details of usage and allowed values, see the style reference . |
featureType optional | Type: string optional The feature, or group of features, to which a styler should be applied. Optional. If featureType is not specified, the value is assumed to be 'all' . For details of usage and allowed values, see the style reference . |
MapMouseEvent interface
google.maps . MapMouseEvent
interface
This object is returned from various mouse events on the map and overlays, and contains all the fields shown below.
Properties | |
---|---|
domEvent | Type: MouseEvent | TouchEvent | PointerEvent | KeyboardEvent | Event The corresponding native DOM event. Developers should not rely on target , currentTarget , relatedTarget and path properties being defined and consistent. Developers should not also rely on the DOM structure of the internal implementation of the Maps API. Due to internal event mapping, the domEvent may have different semantics from the MapMouseEvent (eg a MapMouseEvent "click" may have a domEvent of type KeyboardEvent ). |
latLng optional | Type: LatLng optional The latitude/longitude that was below the cursor when the event occurred. |
Methods | |
---|---|
stop | stop() Parameters: None Return Value: void Prevents this event from propagating further. |
IconMouseEvent interface
google.maps . IconMouseEvent
interface
This object is sent in an event when a user clicks on an icon on the map. The place ID of this place is stored in the placeId member. To prevent the default info window from showing up, call the stop() method on this event to prevent it being propagated. Learn more about place IDs in the Places API developer guide.
This interface extends MapMouseEvent
.
Properties | |
---|---|
placeId optional | Type: string optional The place ID of the place that was clicked. This place ID can be used to query more information about the feature that was clicked. Learn more about place IDs in the Places API developer guide. |
Inherited: domEvent , latLng |
Methods | |
---|---|
Inherited: stop |
MapTypeId constants
google.maps . MapTypeId
constants
Identifiers for common MapTypes. Specify these by value, or by using the constant's name. For example, 'satellite'
or google.maps.MapTypeId.SATELLITE
.
Access by calling const {MapTypeId} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constants | |
---|---|
HYBRID | This map type displays a transparent layer of major streets on satellite images. |
ROADMAP | This map type displays a normal street map. |
SATELLITE | This map type displays satellite images. |
TERRAIN | This map type displays maps with physical features such as terrain and vegetation. |
MapTypeRegistry class
google.maps . MapTypeRegistry
class
A registry for MapType instances, keyed by MapType id.
This class extends MVCObject
.
Access by calling const {MapTypeRegistry} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
MapTypeRegistry | MapTypeRegistry() Parameters: None The MapTypeRegistry holds the collection of custom map types available to the map for its use. The API consults this registry when providing the list of available map types within controls, for example. |
Methods | |
---|---|
set | set(id, mapType) Parameters:
Return Value: None Sets the registry to associate the passed string identifier with the passed MapType. |
Inherited: addListener , bindTo , get , notify , setValues , unbind , unbindAll |
MapRestriction interface
google.maps . MapRestriction
interface
A restriction that can be applied to the Map. The map's viewport will not exceed these restrictions.
Properties | |
---|---|
latLngBounds | Type: LatLngBounds | LatLngBoundsLiteral When set, a user can only pan and zoom inside the given bounds. Bounds can restrict both longitude and latitude, or can restrict latitude only. For latitude-only bounds use west and east longitudes of -180 and 180, respectively, for example, latLngBounds: {north: northLat, south: southLat, west: -180, east: 180} . |
strictBounds optional | Type: boolean optional Bounds can be made more restrictive by setting the strictBounds flag to true . This reduces how far a user can zoom out, ensuring that everything outside of the restricted bounds stays hidden. The default is false , meaning that a user can zoom out until the entire bounded area is in view, possibly including areas outside the bounded area. |
TrafficLayer class
google.maps . TrafficLayer
class
A traffic layer.
This class extends MVCObject
.
Access by calling const {TrafficLayer} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
TrafficLayer | TrafficLayer([opts]) Parameters:
A layer that displays current road traffic. |
Methods | |
---|---|
getMap | getMap() Parameters: None Return Value: Map Returns the map on which this layer is displayed. |
setMap | setMap(map) Parameters:
Return Value: None Renders the layer on the specified map. If map is set to null , the layer will be removed. |
setOptions | setOptions(options) Parameters:
Return Value: None |
Inherited: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
TrafficLayerOptions interface
google.maps . TrafficLayerOptions
interface
TrafficLayerOptions object used to define the properties that can be set on a TrafficLayer.
Properties | |
---|---|
autoRefresh optional | Type: boolean optional Default: true Whether the traffic layer refreshes with updated information automatically. |
map optional | Type: Map optional Map on which to display the traffic layer. |
TransitLayer class
google.maps . TransitLayer
class
A transit layer.
This class extends MVCObject
.
Access by calling const {TransitLayer} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
TransitLayer | TransitLayer() Parameters: None A layer that displays transit lines. |
Methods | |
---|---|
getMap | getMap() Parameters: None Return Value: Map Returns the map on which this layer is displayed. |
setMap | setMap(map) Parameters:
Return Value: None Renders the layer on the specified map. If map is set to null , the layer will be removed. |
Inherited: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
BicyclingLayer class
google.maps . BicyclingLayer
class
A layer showing bike lanes and paths.
This class extends MVCObject
.
Access by calling const {BicyclingLayer} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constructor | |
---|---|
BicyclingLayer | BicyclingLayer() Parameters: None A layer that displays bike lanes and paths and demotes large roads. |
Methods | |
---|---|
getMap | getMap() Parameters: None Return Value: Map Returns the map on which this layer is displayed. |
setMap | setMap(map) Parameters:
Return Value: None Renders the layer on the specified map. If map is set to null , the layer will be removed. |
Inherited: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
CameraOptions interface
google.maps . CameraOptions
interface
Used for setting the map's camera options.
Properties | |
---|---|
center optional | Type: LatLngLiteral | LatLng optional |
heading optional | Type: number optional |
tilt optional | Type: number optional |
zoom optional | Type: number optional |
VisibleRegion interface
google.maps . VisibleRegion
interface
Contains the four points defining the four-sided polygon that is the visible region of the map. On a vector map this polygon can be a trapezoid instead of a rectangle, when a vector map has tilt.
Properties | |
---|---|
farLeft | Type: LatLng |
farRight | Type: LatLng |
latLngBounds | Type: LatLngBounds The smallest bounding box that includes the visible region. |
nearLeft | Type: LatLng |
nearRight | Type: LatLng |
RenderingType constants
google.maps . RenderingType
constants
Access by calling const {RenderingType} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
Constants | |
---|---|
RASTER | Indicates that the map is a raster map. |
UNINITIALIZED | Indicates that it is unknown yet whether the map is vector or raster, because the map has not finished initializing yet. |
VECTOR | Indicates that the map is a vector map. |
MapCapabilities interface
google.maps . MapCapabilities
interface
Object containing a snapshot of what capabilities are currently available for the Map. Note that this does not necessarily mean that relevant modules are loaded or initialized, but rather that the current map has permission to use these APIs. See the properties for a list of possible capabilities.
Properties | |
---|---|
isAdvancedMarkersAvailable optional | Type: boolean optional If true, this map is configured properly to allow for the use of advanced markers. Note that you must still import the marker library in order to use advanced markers. See https://goo.gle/gmp-isAdvancedMarkersAvailable for more information. |
isDataDrivenStylingAvailable optional | Type: boolean optional If true, this map is configured properly to allow for the use of data-driven styling for at least one FeatureLayer. See https://goo.gle/gmp-data-driven-styling and https://goo.gle/gmp-FeatureLayerIsAvailable for more information. |