Конструктор карт гугл стилизация

Обновлено: 27.03.2024

Customize the presentation of the standard Google map by applying your own styles when using the Maps Static API. You can change the visual display of features such as roads, parks, built-up areas, and other points of interest. Change their color or style to emphasize particular content, complement surrounding content on the page, or even hide features completely.

If you want to easily update the same style across multiple apps, look into cloud customization, available in the Google Cloud Console. You will need to create and add a map ID to use cloud customization. We recommend not combining cloud customization and hardcoded styling in the same app, to avoid potential future conflicts.

Examples

The following example displays a map of Brooklyn, US, with styling to color the local roads bright green and the residential areas black. It also inverts the lightness of the labels, so that they stand out better against a dark background. Note that this working example uses URL encoding:

The following example uses styling operations and simplifications to approximate the look of a US road atlas:

US Road Atlas Map Style

Style syntax

To create a customized styled map, include one or more style parameters in the request URL.

Each style declaration may contain the following arguments, separated by pipe characters (" | "):

  • feature (optional) indicates the features to select for this style modification. Features include things on the map, like roads, parks, or other points of interest. If no feature argument is present, the specified style applies to all features.
  • element (optional) indicates the element(s) of the specified feature to select for this style modification. Elements are characteristics of a feature, such as geometry or labels. If no element argument is present, the style applies to all elements of the specified feature.
  • A set of style rules (mandatory) to apply to the specified feature(s) and element(s). The API applies the rules in the order in which they appear in the style declaration. You can include any number of rules, within the normal URL-length constraints of the Maps Static API.

Features

The following style declaration colors all roads on the map:

Here are some common feature selections:

Features, or feature types, are geographic characteristics on the map, including roads, parks, bodies of water, businesses, and more.

The features form a category tree, with all as the root. If you don't specify a feature, all features are selected. Specifying a feature of all has the same effect.

Some features contain child features you specify using a dot notation. For example, landscape.natural or road.local . If you specify only the parent feature, such as road , the styles you specify for the parent apply to all its children, such as road.local and road.highway .

Note that parent features may include some elements that are not included in all of their child features.

The following features are available:

  • all (default) selects all features.
  • administrative selects all administrative areas. Styling affects only the labels of administrative areas, not the geographical borders or fill.
    • administrative.country selects countries.
    • administrative.land_parcel selects land parcels.
    • administrative.locality selects localities.
    • administrative.neighborhood selects neighborhoods.
    • administrative.province selects provinces.
    • landscape.man_made selects man-made features, such as buildings and other structures.
    • landscape.natural selects natural features, such as mountains, rivers, deserts, and glaciers.
    • landscape.natural.landcover selects land cover features, the physical material that covers the earth's surface, such as forests, grasslands, wetlands, and bare ground.
    • landscape.natural.terrain selects terrain features of a land surface, such as elevation, slope, and orientation.
    • poi.attraction selects tourist attractions.
    • poi.business selects businesses.
    • poi.government selects government buildings.
    • poi.medical selects emergency services, including hospitals, pharmacies, police, doctors, and others.
    • poi.park selects parks.
    • poi.place_of_worship selects places of worship, including churches, temples, mosques, and others.
    • poi.school selects schools.
    • poi.sports_complex selects sports complexes.
    • road.arterial selects arterial roads.
    • road.highway selects highways.
    • road.highway.controlled_access selects highways with controlled access.
    • road.local selects local roads.
    • transit.line selects transit lines.
    • transit.station selects all transit stations.
    • transit.station.airport selects airports.
    • transit.station.bus selects bus stops.
    • transit.station.rail selects rail stations.

    Elements

    The following style declaration colors the labels for all local roads:

    Elements are subdivisions of a feature. A road, for example, consists of the graphical line (the geometry) on the map, and also the text denoting its name (a label).

    The following elements are available, but note that a specific feature may support none, some, or all, of the elements:

    • all (default) selects all elements of the specified feature.
    • geometry selects all geometric elements of the specified feature.
      • geometry.fill selects only the fill of the feature's geometry.
      • geometry.stroke selects only the stroke of the feature's geometry.
      • labels.icon selects only the icon displayed within the feature's label.
      • labels.text selects only the text of the label.
      • labels.text.fill selects only the fill of the label. The fill of a label is typically rendered as a colored outline that surrounds the label text.
      • labels.text.stroke selects only the stroke of the label's text.

      Style rules

      Style rules are formatting options which are applied to the features and elements specified within each style declaration.

      The following style declaration applies two style rules to the roads on the map. The first rule applies a color to the roads. The second rule simplifies the display of the roads, so they have thinner lines without outlines:

      Each style declaration must contain one or more operations separated using the pipe (" | ") character. Each operation specifies its argument value using the colon (" : ") character, and all operations apply to the selection in the order in which you specify them.

      The following style options are supported:

      Note: This option sets the hue while keeping the saturation and lightness specified in the default Google style (or in other style options you define on the map). The resulting color is relative to the style of the base map. If Google makes any changes to the base map style, the changes affect your map's features styled with hue . It's better to use the absolute color styler if you can.

      Note: This option sets the lightness while keeping the saturation and hue specified in the default Google style (or in other style options you define on the map). The resulting color is relative to the style of the base map. If Google makes any changes to the base map style, the changes affect your map's features styled with lightness . It's better to use the absolute color styler if you can.

      Note: This option sets the saturation while keeping the hue and lightness specified in the default Google style (or in other style options you define on the map). The resulting color is relative to the style of the base map. If Google makes any changes to the base map style, the changes affect your map's features styled with saturation . It's better to use the absolute color styler if you can.

      Note: This option adjusts the lightness relative to the default Google style, using a gamma curve. If Google makes any changes to the base map style, the changes affect your map's features styled with gamma . It's better to use the absolute color styler if you can.

      Note: This option simply inverts the default Google style. If Google makes any changes to the base map style, the changes affect your map's features styled with invert_lightness . It's better to use the absolute color styler if you can.

      Style rules are applied in the order that you specify. Do not combine multiple operations into a single style operation. Instead, define each operation as a separate entry in the style array.

      Note: Order is important, as some operations are not commutative. Features and/or elements that are modified through style operations (usually) already have existing styles. The operations act on those existing styles, if present.

      The hue, saturation, lightness model

      Styled maps use the hue, saturation, lightness (HSL) model to denote color within the styler operations. Hue indicates the basic color, saturation indicates the intensity of that color, and lightness indicates the relative amount of white or black in the constituent color.

      Gamma correction modifies the lightness over the color space, generally to increase or decrease contrast. Additionally, the HSL model defines color within a coordinate space where hue indicates the orientation within a color wheel, while saturation and lightness indicate amplitudes along different axes. Hues are measured within an RGB color space, which is similar to most RGB color spaces, except that shades of white and black are absent.

      Hue, saturation, lightness model

      While hue takes an HTML hex color value, it only uses this value to determine the basic color - that is, its orientation around the color wheel, not its saturation or lightness, which are indicated separately as percentage changes.

      For example, you can define the hue for pure green as hue:0x00ff00 or hue:0x000100 . Both hues are identical. Both values point to pure green in the HSL color model.


      An RGB Color Wheel

      Additionally, when modifying existing features which already have a color scheme, changing a value such as hue does not change its existing saturation or lightness .

      Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

      Save your style and come back to it later. All saved styles will be listed on the My Styles page.

      Publish your style for the world to see. To reduce spam, we will manually review your style within 48 hours and will list it on the site if we think other users would like it!

      Introduction

      Welcome to the Snazzy Maps editor! With this tool you can create your own Google Maps styles and share them on the site.

      Creating a style

      Google Maps styles are divided into 3 components: features, elements, and styles. These components combine to allow for the detailed creation of map styles.

      Features

      Features are the geographic elements that can be styled on the map. These include land, road, water, and much more. Some features have sub-features and are organized in a tree structure. Styles can be applied to any node in the tree including the "All" node, which changes the styles for every feature. Styles applied to sub-features will override any styles applied on their parents in the tree.

      Elements

      Elements are the geometric properties of the features that can be styled on the map. These include labels, icons, geometric fills, and much more. A combination of feature and element will allow you to target exactly the components you would like to style.

      Styles

      Styles are the formatting options applied to your selected feature and element. These are grouped into sections: visibility, color, color options, and advanced options. Each section has a Reset button which will clear out any styles that have been changed in that section. If any styles have been modified from the default, a helpful dot is added to the feature and element nodes to signify that there are styles applied to those components.

      Viewing style code

      Once you have finished creating a map style you can view the generated code. By clicking the View Code tab you will be able to view the JSON style array that corresponds with your map style. Just copy and paste this into your code to use your style. If you are lost on how to use this code check out our FAQs for a little help.

      Saving

      You can save your style at any point. Simply click on the Save tab, and enter in a name for your style. All Saved styles will appear on the My Styles page.

      Publishing

      If you are finished with your style and would like to share it with the world click the Publish tab. Enter in a name and a description, up to 3 tags and colors that describe your style, and click publish. Your style will now be available for everyone on the site. If you ever want to unpublish your style or tweak the properties simply open up the Publish tab again.

      Downloading Images

      Registered users can now download an image of a Snazzy Maps style with our new Download Image feature. Adjust the image size and scale, pan and preview the map, and download your image.

      During our initial beta release, registered users can download 10 images per day while we evaluate user feedback and demand. This may change as we update the feature.

      Any feedback to improve this feature would be greatly appreciated.

      By downloading these images, you agree to follow the Google Maps API terms of service.

      Download an image of this Snazzy Maps style. Find out more about downloading images.

      If you want to change the language of the map, please update your account settings.

      You have 0 downloads remaining for today. Find out more about downloading images.

      image

      В первый раз столкнувшись с внедрением и кастомизацией Google Maps, я не нашел единой статьи, рассматривающей все необходимые моменты — информацию пришлось искать по крупицам, а что-то выдумывать самому. После чего и было решено написать эту статью, чтобы люди, ранее не работавшие со стилизацией Google Maps, но при этом ограниченные временными рамками (а может, и желанием) для полноценного изучения API, смогли быстро получить необходимую информацию и материалы. Тем более, что и те, кто обладает определенным опытом, смогут почерпнуть для себя из этой статьи какую-нибудь интересную фишку, к примеру — параллакс для элементов информационного окна.

      В этой статье мы рассмотрим:

      1. Внедрение Google Maps на сайт

      • Добавление через вставку iframe в разметку
      • Добавление через API
      • Инициализация маркера
      • Анимация маркера
      • Изображение маркера
      • Добавление информационного окна
      • Открытие информационного окна
      • Кастомизация элементов информационного окна
      • Параллакс-эффект для элементов в информационном окне
      • Изменение цвета объектов карты
      • Кастомизация элементов управления
      • Маска для карты

      Добавление через вставку iframe в разметку

      Если у вас нет необходимости изменять маркер, делать кастомное информационное окно или еще каким-либо образом воздействовать на карту, для ее добавления достаточно сделать следующее:

      • Открыть Google Maps.
      • Найти интересующий объект (например, введя адрес в поиске, либо нажав на нужное название правой кнопкой мыши и выбрав пункт в контекстном меню «Что здесь?»)

      image

      после чего кликнуть на гамбургер:

      image

      Затем находим кнопку «Ссылка/код»:

      image

      Копируем код для вставки:

      image

      Но если необходимо произвести какие-либо манипуляции, нам понадобится ключ. Если его нет рядом, можно получить тут: ссыль

      Встраиваем его в адрес вместо YOUR_API_KEY :


      Если нужно вызывать коллбэк после загрузки api, после ключа надо будет дописать YOUR_API_KEY&callback=initMap с названием вашей функции. Подключаем скрипт на странице и создаем в разметке блок для будущей карты:


      Теперь необходимо инициализировать карту:


      Координаты можно узнать при помощи опции «Что здесь», описанной выше.

      Свойства, которые могут сразу понадобиться:

      • zoom: number — определяет первоначальный масштаб.
      • disableDefaultUI: boolean – убирает элементы управления.
      • scrollwheel: boolean — отключает масштабирование колесиком мыши (бывает полезно, если карта на всю ширину страницы и перебивает прокрутку вниз).

      Для начала добавим маркер:


      position (обязательно) указывает начальное положение маркера. Если указать те же координаты, что и для карты, то маркер будет по центру экрана. Сместить маркер можно изменив значение координат, либо сменив положение самой карты относительно видимой области (родительского блока).
      map (не обязательно) указывает карту, на которой помещается маркер.

      Для маркера можно задать анимацию:

      • DROP – после загрузки карты маркер падает сверху.
      • BOUNCE – маркер подпрыгивает на месте.

      Анимацию можно задать при инициализации маркера, добавить или убрать, вызвав метод setAnimation() .

      Пример анимации маркера при закрытии информационного окна и прекращении при открытии:

      Изображение маркера можно изменить, задав адрес картинки для свойства icon .


      3. Кастомизация информационного окна

      Добавление информационного окна

      В кастомное информационное окно можно добавить любую разметку через свойство content :


      Открытие информационного окна

      Чтобы информационное окно было видно сразу, надо вызвать метод open() :


      Также следует добавить вызов окна при клике на маркер (в противном случае мы не сможем открыть попап):


      Кастомизация элементов информационного окна

      Информационное окно может быть как кастомное, так и стандартное. В кастомное мы можем добавить любые элементы и работать с ними, возможности ограничены лишь фантазией.

      Основная проблема, с которой можно столкнуться при кастомизации любого из типов – края (белая область) вокруг контента и стрелочка. Эти элементы не поддаются css выборке.

      image

      Решить проблему можно при помощи псевдоэлементов для доступных блоков. Также, если по какой-либо причине нет возможности использовать лишний псевдоэлемет, рамочку можно убрать при помощи тени.


      Но обо всем по порядку:

      .gm-style-iw — основной блок, в нем находится контент. На скриншоте, расположенном выше, этот блок имеет черный фон.
      .poi-info-window — обертка для текста в стандартном информационном окне, находится внутри. .gm-style-iw
      .gm-style-iw + div – крестик.

      Как теперь повлиять на область вне блока контента? Выйти за его пределы. В первую очередь надо добавить свойство, которое сделает видимыми блоки, выходящие за границы:


      Теперь для .gm-style-iw , или блоков внутри можно создать псевдоэлементы для перекрытия фона и стрелочки:

      image

      Параллакс-эффект для элементов в информационном окне

      Тут возникает небольшая проблема, связанная с тем, что объекты карты создаются динамически, и нельзя просто так взять и прикрепить к ним обработчик, а клонировать блок при помощи .clone(true) в контент информационного окна с переносом обработчиков нам не позволит API.

      Как вариант, можно проверять наличие элемента и сохранять после появления:


      Теперь просто добавим код, смещающий блок по горизонтали в зависимости от положения курсора:


      Если клик по динамическому элементу нужно обработать, просто ставим обработчик на обертку и ловим объект на всплытии:


      4. Кастомизация карты

      Изменение цвета объектов карты

      Для стилизации карты используется массив стилей, в котором указывается селектор и css-свойство, которое необходимо применить.

      Пример настроек, окрашивающих воду в фиолетовый цвет:


      Для настройки стилей проще всего использовать специализированный сервис, к примеру Google Maps APIs Styling Wizard. Для детальной настройки карты жмем «More options»:

      image

      image

      Копируем полученный json:

      image

      Если массив стилей очень большой, его можно поместить в отдельный .json файл и применить стили после его загрузки:


      В конечном итоге получаем вот такие настройки карты:


      Кастомизация элементов управления

      image

      Кнопки «Карта» и «Спутник» находятся в блоке с классом .gm-style-mtc

      image

      Кнопки увеличения и уменьшения изображения в блоке с классом .gmnoprint

      image

      Кнопка режима просмотра улиц имеет класс .gm-svpc

      image

      Используя эти классы, можно сделать с элементами управления все, что душе угодно. В данном случае я скрыл элементы управления, но для примера изменил цвет:

      Ну, и на закуску — очень простая вещь, но может для кого-нибудь окажется в новинку. По сути — просто блок на весь размер карты, либо являющийся картинкой, либо с фоновым изображением. Также есть свойство mask-image , но оно поддерживается не всеми браузерами.

      Единственное, на что тут следует обратить внимание — css свойство pointer-events , которое на маске должно быть в значении none . Это позволит не учитывать этот блок в событиях мыши (проще говоря, кликать и скроллить сквозь этот блок).

      image

      На этом быстрый старт Google Maps окончен. Надеюсь, эта статья оказалась для вас полезной.

      Overview

      Google Maps Platform offers Cloud-based maps styling features that make it easy to style, customize, and manage your maps using the Google Cloud Console, letting you create a customized map experience for your users without having to update your apps' code each time you make a style change.

      Styles created before September 15, 2020 will not display Google Maps enhanced natural features. To use Google Maps enhanced natural features support for your map styling, you must create a map Style.

      Cloud-based maps styling lets you create and edit map styles for any of your apps that use Google Maps, without requiring any changes to your code once the map ID is in place. All style changes can be done in the Cloud Console, with no coding skills required. Change the appearance and color of many map elements such as roads, buildings, bodies of water, points of interest, and transit routes.

      These features include:

      While Cloud-based maps styling is available on Maps SDK for Android 1 , Maps SDK for iOS, JavaScript, and Maps Static API, not all features will be visible on all platforms.

      Before you begin

      • To create or manage any map IDs or map Styles in a given Google Cloud project, you must hold either the Owner or Editor IAM role on the project.
      • All platforms: Before adding a map ID to use Cloud-based maps styling on an existing map that is customized with hard-coded styling, such as JSON or URL query parameters, we recommend you remove the hard-coded styling to avoid potential conflict with future functionality. You can import your JSON styling into a new map style.
        • On Android, update the MapStyleOptions
        • On iOS, update the GMSMapStyle class
        • On JavaScript, remove the MapTypeStyle styling
        • On Maps Static, remove the style parameter

        Billing

        Using Cloud-based maps styling requires a map ID. On Maps SDK for Android, Maps SDK for iOS, and JavaScript, using a map ID incurs a charge against the Dynamic Maps SKU. On the Maps Static API, using a map ID incurs a charge against the Static Maps SKU.

        Demos and examples

        Android

        Run the ApiDemos sample app

        To run the ApiDemos sample app, see the GitHub sample (Java | Kotlin) and view the CloudBasedMapStylingActivity demo (Java | Kotlin).

        You can find a Java and Kotlin sample application that demonstrates how to style your Android map from the cloud.

        Known Issues

        Once your app is delivered to customers, custom styles for maps with map IDs can be updated from Google Cloud Console. The new styles will be reflected in your app in a few hours.

        To make sure new custom styles show up immediately for testing purposes, clear app data from your test device. For more information on clearing data from your device, see Android Help - Free Up Space.

        Note that settings can vary by phone. For more information, contact your device manufacturer.

        Run the ApiDemos sample app

        To run the ApiDemos sample app, see the GitHub sample GoogleMap sample app and view the CloudBasedMapStylingViewController project (GitHub sample for Swift | Objective-C).

        Optional Cloud Styling CocoaPod or GitHub demo

        Instead of starting from scratch, you can try out our Cloud-based maps styling demo, which is installed by following the instructions in the Using the Google Maps Beta CocoaPod section.

        Alternatively, you can find an Objective-C sample application that demonstrates how to style your iOS map from the cloud here.

        Building the Beta demo app

        In Xcode, press the compile button to build and then run the current scheme. The build produces an error, prompting you to enter your API key in the SDKDemoAPIKey.h file.

        If you don't yet have an API key, follow these instructions to set up a project on the Cloud Console and get an API key. When configuring the key on the Cloud Console, you can specify your app's bundle identifier to ensure that only your app can use the key. The default bundle identifier of the SDK samples app is com.example.GoogleMapsDemos .

        Edit the SDKDemoAPIKey.h file and paste your API key into the definition of the kAPIKey constant:

        If Xcode prompts you to unlock the SDKDemoAPIKey.h file for editing, choose Unlock.

        Remove the following line:

        Build and run the project.

        Cloud-based maps styling map demo

        The CloudStyling demo shows how to style the map by using a style set on Google Cloud Console.

        When the demo application launches, click on the Map Customization demo in the Beta Samples section at the top of the list.

        Click on Style Map to see the effect of loading different Map IDs.

        You can try adding your own style as well ("Style Map" > "Add a new Map ID"), and see the map update with your custom styled map.

        JavaScript

        This is a basic example of loading a custom styled map using a map ID. In this case, the Maps JavaScript references map ID 8e0a97af9386fef when the map is loaded, and automatically applies the map style currently associated with that map ID.

        A map Style is a set of customizations that can be associated with a map ID, which is referenced in app code to display the customized map.

        While it isn't required to have a map ID before creating a style, you must associate it with a map ID and add the map ID to your app before you can use your style. This is the only point in the map-style life cycle where anyone will need to interact with the application code.

        Create a style

        Create a map style using one of these methods:

        • creating a new style, either using default Google Map styles or based off of a suggested template
        • duplicating an existing style
        • importing JSON styling

        Create a new style

        1. In the Google Cloud Console, go to the Map Styles page.
        2. Select Create New Map Style, and choose the Google Map radio button.
        3. Select the blue Save button at the bottom of the page.
        4. In the Save and Publish Map modal, enter a map name and optional description, and select Save.

        You are taken to your new style's main page.

        Duplicate an existing style

        1. In the Google Cloud Console, go to the Map Styles page.
        2. Select one of your existing styles, and go to Duplicate.
        3. In the Duplicate Map Style modal, enter a new map name and, if desired, a description.
        4. Select Save in the lower right corner.

        You are taken to your new style's main page.

        Import JSON styling

        1. In the Google Cloud Console, go to the Map Styles page.
        2. Select Create style.
        3. Under Create your own style, select the Import JSON radio button.
        4. Paste your valid JSON styling code into the field.
          • If your JSON is invalid, you see a notice in capital letters just below the JSON field.
          • If your JSON is valid, you see a preview of the pasted style, and the blue SAVE button is available.
        5. Select SAVE.

        You are taken to your new style's main page.

        Update style details

        Once you've created a map style, you can edit, duplicate, rename, delete, or add map IDs to it using the options at the top of the style's main page.

        A screenshot of the main page for a single map style, showing the name of the map, the controls to customize or rename or duplicate or delete a style, a picture showing the style applied to a mapped area, and a notice saying that there are no map IDs associated with this style and a button labeled

        • Continue customizing or view style details by selecting Customize style.
          • To edit feature and element styles, see the Map Style editor overview or view some step-by-step styling examples.

          Associate or remove map IDs on your style

          Styles can be associated with multiple map IDs, since the same style can be applied across multiple Google Maps apps. However, each map ID may be associated with only one style.

          1. On the Map Styles page, select a style.
          2. Select either the Add Map IDs button (for styles with no associated map IDs) or the pencil icon (for styles that already have at least one associated map ID.) This opens the Add / Edit Map IDs pane.
          3. Check the box next to a map ID to associate with this style, or uncheck a checked box to remove the association.
          4. Select Save.

          To use your Cloud-based map style, add the map ID to your app.

          Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

          Читайте также: