Класс карты
google.maps . Map
Класс google.maps . Map
Этот класс расширяет MVCObject
.
Доступ осуществляется путем вызова const {Map} = await google.maps.importLibrary("maps")
. См. раздел Библиотеки в Maps JavaScript API .
Конструктор | |
---|---|
Map | Map(mapDiv[, opts]) Параметры:
Создает новую карту внутри заданного HTML-контейнера, который обычно является элементом DIV . |
Константы | |
---|---|
DEMO_MAP_ID | Идентификатор карты, который можно использовать для примеров кода, требующих идентификатор карты. Этот идентификатор карты не предназначен для использования в рабочих приложениях и не может использоваться для функций, требующих облачной настройки (например, Cloud Styling). |
Характеристики | |
---|---|
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(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 будет иметь значение false. |
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 |
События | |
---|---|
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() Аргументы: Нет Это событие вызывается при изменении типа рендеринга. |
tilesloaded | function() Аргументы: Нет Это событие вызывается, когда видимые плитки завершили загрузку. |
tilt_changed | function() Аргументы: Нет Это событие вызывается при изменении свойства наклона карты. |
zoom_changed | function() Аргументы: Нет Это событие вызывается при изменении свойства масштабирования карты. |
| function(event) Аргументы:
Это событие вызывается, когда пользователь щелкает правой кнопкой мыши на карте. |
Интерфейс MapOptions
google.maps . MapOptions
Интерфейс google.maps . MapOptions
Объект MapOptions, используемый для определения свойств, которые можно установить на карте.
Характеристики | |
---|---|
backgroundColor optional | Тип: string optional Цвет, используемый для фона div-карты. Этот цвет будет виден, когда плитки еще не загружены при панорамировании пользователем. Эту опцию можно установить только при инициализации карты. |
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 Исходный MapTypeId. По умолчанию используется ROADMAP . |
maxZoom optional | Тип: number optional Максимальный уровень масштабирования, который будет отображаться на карте. Если этот параметр опущен или установлен в значение null , вместо него используется максимальный масштаб текущего типа карты. Допустимые значения масштабирования — это числа от нуля до поддерживаемого максимального уровня масштабирования . |
minZoom optional | Тип: number optional Минимальный уровень масштабирования, который будет отображаться на карте. Если этот параметр опущен или установлен в значение null , вместо него используется минимальный масштаб текущего типа карты. Допустимые значения масштабирования — это числа от нуля до поддерживаемого максимального уровня масштабирования . |
noClear optional | Тип: boolean optional Если true , не очищайте содержимое div Map. |
| Тип: boolean optional Включенное/выключенное состояние элемента управления панорамированием. |
| Тип: PanControlOptions optional Параметры отображения элемента управления панорамированием. |
restriction optional | Тип: MapRestriction optional Определяет границу, ограничивающую область карты, доступную пользователям. Если этот параметр установлен, пользователь может панорамировать и масштабировать изображение только тогда, когда вид с камеры остается в пределах границы. |
rotateControl optional | Тип: boolean optional Включенное/выключенное состояние элемента управления «Поворот». |
rotateControlOptions optional | Тип: RotateControlOptions optional Параметры отображения элемента управления «Поворот». |
scaleControl optional | Тип: boolean optional Исходное включенное/отключенное состояние элемента управления «Масштаб». |
scaleControlOptions optional | Тип: ScaleControlOptions optional Первоначальные параметры отображения элемента управления «Масштаб». |
scrollwheel optional | Тип: boolean optional Если false , отключает масштабирование карты с помощью колеса прокрутки мыши. Колесо прокрутки включено по умолчанию. Примечание . Использование этого свойства не рекомендуется . Чтобы отключить масштабирование с помощью колеса прокрутки, вы можете использовать свойство |
streetView optional | Тип: StreetViewPanorama optional StreetViewPanorama , отображаемая при размещении человечка Street View на карте. Если панорама не указана, StreetViewPanorama по умолчанию будет отображаться в div карты при отбрасывании человечка. |
streetViewControl optional | Тип: boolean optional Исходное включенное/отключенное состояние элемента управления Street View Pegman. Этот элемент управления является частью пользовательского интерфейса по умолчанию, и для него должно быть установлено значение false при отображении типа карты, на котором не должно отображаться наложение дорог Street View (например, тип карты, отличный от карты Земли). |
streetViewControlOptions optional | Тип: StreetViewControlOptions optional Первоначальные параметры отображения элемента управления «Человеком» в просмотре улиц. |
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">
<button slot="control-block-start-inline-end">Custom Control</button>
</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 Идентификатор карты. Дополнительную информацию см. в документации Map ID . HTML-атрибут:
|
zoom | Тип: number optional Уровень масштабирования карты. HTML-атрибут:
|
Методы | |
---|---|
| addEventListener(type, listener[, options]) Параметры:
Возвращаемое значение: void Устанавливает функцию, которая будет вызываться всякий раз, когда указанное событие доставляется в цель. См. addEventListener . |
| removeEventListener(type, listener[, options]) Параметры:
Возвращаемое значение: void Удаляет из цели прослушиватель событий, ранее зарегистрированный с помощью addEventListener. См. RemoveEventListener . |
События | |
---|---|
gmp-zoomchange | function(event) Аргументы:
Это событие вызывается при изменении свойства масштабирования карты. |
Интерфейс MapElementOptions
google.maps . MapElementOptions
Интерфейс google.maps . MapElementOptions
Объект MapElementOptions, используемый для определения свойств, которые можно задать для MapElement.
Характеристики | |
---|---|
center optional | Тип: LatLng | LatLngLiteral optional Начальный центр карты. |
mapId optional | Тип: string optional Идентификатор карты. Этот параметр нельзя установить или изменить после создания экземпляра карты. |
zoom optional | Тип: number optional Начальный уровень масштабирования карты. Допустимые значения масштабирования — это числа от нуля до поддерживаемого максимального уровня масштабирования . Большие значения масштабирования соответствуют более высокому разрешению. |
Класс ZoomChangeEvent
google.maps . ZoomChangeEvent
Класс google.maps . ZoomChangeEvent
Это событие создается в результате мониторинга изменения масштаба.
Этот класс расширяет Event
.
Доступ осуществляется путем вызова const {ZoomChangeEvent} = await google.maps.importLibrary("maps")
. См. раздел Библиотеки в Maps JavaScript API .
Интерфейс 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 . |
Интерфейс ограничения карты
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 , что означает, что пользователь может уменьшать масштаб до тех пор, пока не будет видна вся ограниченная область, возможно, включая области за пределами ограниченной области. |
Класс ТрафикЛайер
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 | 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 .
Конструктор | |
---|---|
Map | Map(mapDiv[, opts]) Параметры:
Creates a new map inside of the given HTML container, which is typically a DIV element. |
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). |
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). |
Методы | |
---|---|
fitBounds | fitBounds(bounds[, padding]) Параметры:
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(datasetId) Параметры:
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) Параметры:
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) Параметры:
Return Value: None Immediately sets the map's camera to the target camera options, without animation. |
panBy | panBy(x, y) Параметры:
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) Параметры:
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]) Параметры:
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) Параметры:
Return Value: None |
setClickableIcons | setClickableIcons(value) Параметры:
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) Параметры:
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) Параметры:
Return Value: None |
setOptions | setOptions(options) Параметры:
Return Value: None |
setStreetView | setStreetView(panorama) Параметры:
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) Параметры:
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) Параметры:
Return Value: None Sets the zoom of the map. |
Inherited: addListener , bindTo , get , notify , set , setValues , unbind , unbindAll |
События | |
---|---|
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. Включено по умолчанию. 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. |
| Type: boolean optional The enabled/disabled state of the Pan control. |
| Type: PanControlOptions optional The display options for the Pan control. |
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. For example:
<gmp-map center="37.4220656,-122.0840897" zoom="10" map-id="DEMO_MAP_ID">
<button slot="control-block-start-inline-end">Custom Control</button>
</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 The center latitude/longitude of the map. HTML attribute:
|
innerMap | Type: Map A reference to the Map that the MapElement uses internally. |
mapId | Type: string optional The Map ID of the map. See the Map ID documentation for more information. HTML attribute:
|
zoom | Type: number optional The zoom level of the map. HTML attribute:
|
Методы | |
---|---|
| addEventListener(type, listener[, options]) Параметры:
Return Value: void Sets up a function that will be called whenever the specified event is delivered to the target. See addEventListener |
| removeEventListener(type, listener[, options]) Параметры:
Return Value: void Removes an event listener previously registered with addEventListener from the target. See removeEventListener |
События | |
---|---|
gmp-zoomchange | function(event) Arguments:
This event is fired when the map zoom property changes. |
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. |
ZoomChangeEvent class
google.maps . ZoomChangeEvent
class
This event is created from monitoring zoom change.
This class extends Event
.
Access by calling const {ZoomChangeEvent} = await google.maps.importLibrary("maps")
. See Libraries in the Maps JavaScript API .
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. Необязательный. 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. Необязательный. 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. |
Методы | |
---|---|
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 |
Методы | |
---|---|
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 .
Конструктор | |
---|---|
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. |
Методы | |
---|---|
set | set(id, mapType) Параметры:
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 .
Конструктор | |
---|---|
TrafficLayer | TrafficLayer([opts]) Параметры:
A layer that displays current road traffic. |
Методы | |
---|---|
getMap | getMap() Parameters: None Return Value: Map Returns the map on which this layer is displayed. |
setMap | setMap(map) Параметры:
Return Value: None Renders the layer on the specified map. If map is set to null , the layer will be removed. |
setOptions | setOptions(options) Параметры:
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 .
Конструктор | |
---|---|
TransitLayer | TransitLayer() Parameters: None A layer that displays transit lines. |
Методы | |
---|---|
getMap | getMap() Parameters: None Return Value: Map Returns the map on which this layer is displayed. |
setMap | setMap(map) Параметры:
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 .
Конструктор | |
---|---|
BicyclingLayer | BicyclingLayer() Parameters: None A layer that displays bike lanes and paths and demotes large roads. |
Методы | |
---|---|
getMap | getMap() Parameters: None Return Value: Map Returns the map on which this layer is displayed. |
setMap | setMap(map) Параметры:
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. |