Конструктор карт гугл api

Обновлено: 21.07.2024


All Maps Embed API requests are available at no charge with unlimited usage. For more information, see Usage and Billing.

Before you begin

To create an embedded map on your web page, complete the required setup steps by clicking through the following tabs:

Step 1


In the Google Cloud Console, on the project selector page, click Create Project to begin creating a new Cloud project.

Make sure that billing is enabled for your Cloud project. Confirm that billing is enabled for your project.

Google Cloud offers a $0.00 charge trial. The trial expires at either end of 90 days or after the account has accrued $300 worth of charges, whichever comes first. Cancel anytime. Google Maps Platform features a recurring $200 monthly credit. For more information, see Billing account credits and Billing.

Cloud SDK

Read more about the Google Cloud SDK , Cloud SDK installation , and the following commands:

Step 2

To use Google Maps Platform, you must enable the APIs or SDKs you plan to use with your project.


Cloud SDK

Read more about the Google Cloud SDK , Cloud SDK installation , and the following commands:

Step 3

This step only goes through the API Key creation process. If you use your API Key in production, we strongly recommend that you restrict your API key. You can find more information in the product-specific Using API Keys page.

The API key is a unique identifier that authenticates requests associated with your project for usage and billing purposes. You must have at least one API key associated with your project.

To create an API key:


Go to the Google Maps Platform > Credentials page.

Cloud SDK

Read more about the Google Cloud SDK , Cloud SDK installation , and the following commands:

Generating an iframe

Click through the following options and add a location and API key to generate an iframe for your webpage. For additional parameters and options, see Embedding a map.

Testing your iframe

To see your iframe in an HTML browser window:

  1. Open your default text editor. You should have text editors such as TextEdit or Microsoft Windows Notepad installed on your device by default.
  2. Create an HTML file and name it index.html .

Add the following code with the iframe you generated above:

Save your index.html HTML file.

Load the HTML file in a web browser by dragging it from your desktop onto your browser; alternatively, double-clicking the file works on most operating systems.

Congratulations! You just set up and built a map using the Maps Embed API.

Cleaning up

You can delete your Google Cloud project to stop billing for all the resources used within that project.

Next steps

Start developing with the Maps Embed API by setting up your Google Cloud project:

For a list of additional parameters and options you can add in your iframe:

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.

There are three steps to creating a Google map with a marker on your web page:

You need a web browser. Choose a well-known one like Google Chrome (recommended), Firefox, Safari or Edge, based on your platform from the list of supported browsers.

Step 1: Create an HTML page

Here's the code for a basic HTML web page:

Note that this is a very basic page with a heading level three ( h3 ) and a single div element. You can add any content you like to the web page.

Understanding the code

The code below creates an HTML page consisting of a head and a body.

You can add a heading level three above the map using the code below.

The code below defines an area of the page for your Google map.

At this stage of the tutorial, the div appears as just a grey block, because you have not yet added a map. The code below describes the CSS that sets the size and color of the div .

In the above code, the style element sets the div size for your map. Set the div width and height to greater than 0px for the map to be visible. In this case, the div is set to a height of 400 pixels, and width of 100% to display the across the width of your web page.

Step 2: Add a map with a marker

This section shows you how to load the Maps JavaScript API into your web page, and how to write your own JavaScript that uses the API to add a map with a marker on it.



Try Sample

Understanding the code

In the code below, the script loads the API from the specified URL.

In the above code, the callback parameter executes the initMap function after the API loads. The async attribute allows the browser to continue to parse the remainder of your page while the API loads. Once it has loaded, the browser will pause and immediately execute the script. The key parameter contains your API key.

See Step 3: Get an API key for instructions on getting your own API key later.

The code below contains the initMap function that initializes and adds the map when the web page loads. Use a script tag to include your own JavaScript which contains the initMap function.

Add the document.getElementById() function to find the map div on the web page.

The code below constructs a new Google maps object, and adds properties to the map including the center and zoom level. See the documentation for other property options.



In the above code, new google.maps.Map() creates a new Google maps object. The center property tells the API where to center the map.

The zoom property specifies the zoom level for the map. Zoom: 0 is the lowest zoom, and displays the entire earth. Set the zoom value higher to zoom in to the earth at higher resolutions.

The code below puts a marker on the map. The position property sets the position of the marker.



Learn more about markers:

Step 3: Get an API key

This section explains how to authenticate your app to the Maps JavaScript API using your own API key.

Follow these steps to get an API key:

Create or select a project.

Click Continue to enable the API and any related services.

On the Credentials page, get an API key (and set the API key restrictions). Note: If you have an existing unrestricted API key, or a key with browser restrictions, you may use that key.

To prevent quota theft and secure your API key, see Using API Keys.

Enable billing. See Usage and Billing for more information.

Copy the entire code of this tutorial from this page, to your text editor.

Replace the value of the key parameter in the URL with your own API key (that's the API key that you've just obtained).

Save this file with a name that ends with .html , like index.html .

Load the HTML file in a web browser by dragging it from your desktop onto your browser. Alternatively, double-clicking the file works on most operating systems.

Tips and troubleshooting

  • You can tweak options like style and properties to customize the map. For more information on customizing maps, read the guides to styling, and drawing on the map.
  • Use the Developer Tools Console in your web browser to test and run your code, read error reports and solve problems with your code.
  • Use the following keyboard shortcuts to open the console in Chrome:
    Command+Option+J (on Mac), or Control+Shift+J (on Windows).

Follow the steps below to get the latitude and longitude coordinates for a location on Google Maps.

  1. Open Google Maps in a browser.
  2. Right-click the exact location on the map for which you require coordinates.
  3. Select What's here from the context menu that appears. The map displays a card at the bottom of the screen. Find the latitude and longitude coordinates in the last row of the card.

You can convert an address into latitude and longitude coordinates using the Geocoding service. The developer guides provide detailed information on getting started with the Geocoding service.

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.

Build dynamic, interactive, deeply customized maps, location, and geospatial experiences for your web apps.

Get Started

Get started with Google Maps Platform

Follow the Google Maps Platform getting started guide to create an account, generate an API key, and start building.

Build your first map with a marker

Customize the style of your map

Customize just about every aspect of the map, including roads, geographical features, points of interest, and more.

Add info windows to your markers


Map types



UI controls


WebGL overlay

Info windows


Custom overlays

Ground overlays

Data layer

Custom styling

Tilt & rotation

Marker clustering



Libraries overview

Drawing library

Geometry library

Places library

Local Context library (beta)

Visualization library


Directions service

Distance Matrix service

Elevation service

Geocoding service

Maximum Zoom Imagery service

Street View service

Example apps

Searching for Places

Styling the map for dark mode

Customizing marker icons

Using custom overlays

Displaying a traffic layer

Tilting & rotating the map

Help & support

Stack Overflow

Get help. Give Help. Build Maps karma.

Issue Tracker

Report a bug or open a feature request.

Platform status

Find out about platform incidents and outages.


Get help from the Google Maps Platform team.

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.

The Maps JavaScript API lets you customize maps with your own content and imagery for display on web pages and mobile devices. The Maps JavaScript API features four basic map types (roadmap, satellite, hybrid, and terrain) which you can modify using layers and styles, controls and events, and various services and libraries.


This documentation is designed for people familiar with JavaScript programming and object-oriented programming concepts. You should also be familiar with Google Maps from a user's point of view. There are many JavaScript tutorials available on the Web.

This conceptual documentation is designed to let you quickly start exploring and developing applications with the Maps JavaScript API. We also publish the Maps JavaScript API Reference.

Hello, World

The easiest way to start learning about the Maps JavaScript API is to see a simple example. The following example displays a map centered on Sydney, New South Wales, Australia.



Try Sample

Even in this simple example, there are a few things to note:

  1. We declare the application as HTML5 using the declaration.
  2. We create a div element named "map" to hold the map.
  3. We define a JavaScript function that creates a map in the div .
  4. We load the Maps JavaScript API using a script tag.

These steps are explained below.

Declaring your application as HTML5

We recommend that you declare a true DOCTYPE within your web application. Within the examples here, we've declared our applications as HTML5 using the simple HTML5 DOCTYPE as shown below:

Most current browsers will render content that is declared with this DOCTYPE in "standards mode" which means that your application should be more cross-browser compliant. The DOCTYPE is also designed to degrade gracefully; browsers that don't understand it will ignore it, and use "quirks mode" to display their content.

Note that some CSS that works within quirks mode is not valid in standards mode. In specific, all percentage-based sizes must inherit from parent block elements, and if any of those ancestors fail to specify a size, they are assumed to be sized at 0 x 0 pixels. For that reason, we include the following declaration:

This CSS declaration indicates that the map container (with id map ) should take up 100% of the height of the HTML body. Note that we must specifically declare those percentages for and as well.

Loading the Maps JavaScript API

The Maps JavaScript API is loaded using a script tag, which can be added inline in your HTML file or dynamically using a separate JavaScript file. We recommend that you review both approaches, and choose the one that is most appropriate for how the code in your project is structured.

Inline Loading

To load the Maps JavaScript API inline in an HTML file, add a script tag as show below.

Dynamic Loading

To dynamically load the Maps JavaScript API inline using a separate JavaScript file, see the example below. This approach allows you to handle all of your code for working with the API from a separate .js file, and is the equivalent of adding the script tag inline.

Dynamic Loading

The @googlemaps/js-api-loader package is available to make a more seamless dynamic loading experience. It can be installed through NPM with the following:

This package can be imported into the application with:

The loader exposes a Promise and callback interface. The following demonstrates usage of the default Promise method load() .



Script Tag Attributes

Notice in the examples above that several attributes are set on the script tag, which are recommended. The following is an explanation of each attribute.

  • src : The URL where the Maps JavaScript API is loaded from, including all of the symbols and definitions you need for using the Maps JavaScript API. The URL in this example has two parameters: key , where you provide your API key, and callback , where you specify the name of a global function to be called once the Maps JavaScript API loads completely. Read more about URL parameters.
  • async : Asks the browser to asynchronously download and execute the script. When the script is executed, it will call the function specified using the callback parameter.


When loading the Maps JavaScript API via the URL you may optionally load additional libraries through use of the libraries URL parameter. Libraries are modules of code that provide additional functionality to the main Maps JavaScript API but are not loaded unless you specifically request them. For more information, see Libraries in the Maps JavaScript API.

Synchronously loading the API

In the script tag that loads the Maps JavaScript API, it is possible to omit the defer attribute and the callback parameter. This will cause the loading of the API to block until the API is downloaded.

This will probably slow your page load. But it means you can write subsequent script tags assuming that the API is already loaded.

Important: Consult the Content Security Policy guide to learn more about configuring CSP for the Maps JavaScript API.

Map DOM Elements

For the map to display on a web page, we must reserve a spot for it. Commonly, we do this by creating a named div element and obtaining a reference to this element in the browser's document object model (DOM).

In the example above, we used CSS to set the height of the map div to "100%". This will expand to fit the size on mobile devices. You may need to adjust the width and height values based on the browser's screensize and padding. Note that divs usually take their width from their containing element, and empty divs usually have 0 height. For this reason, you must always set a height on the explicitly.

Map Options

There are two required options for every map: center and zoom .

Zoom Levels

The initial resolution at which to display the map is set by the zoom property, where zoom 0 corresponds to a map of the Earth fully zoomed out, and larger zoom levels zoom in at a higher resolution.

Offering a map of the entire Earth as a single image would either require an immense map, or a small map with very low resolution. As a result, map images within Google Maps and the Maps JavaScript API are broken up into map "tiles" and "zoom levels." At low zoom levels, a small set of map tiles covers a wide area; at higher zoom levels, the tiles are of higher resolution and cover a smaller area. The following list shows the approximate level of detail you can expect to see at each zoom level:

  • 1: World
  • 5: Landmass/continent
  • 10: City
  • 15: Streets
  • 20: Buildings

The following three images reflect the same location of Tokyo at zoom levels 0, 7 and 18.

For information on how the Maps JavaScript API loads tiles based on the current zoom level, see the guide to map and tile coordinates.

The Map Object

The JavaScript class that represents a map is the Map class. Objects of this class define a single map on a page. (You may create more than one instance of this class — each object will define a separate map on the page.) We create a new instance of this class using the JavaScript new operator.

When you create a new map instance, you specify a HTML element in the page as a container for the map. HTML nodes are children of the JavaScript document object, and we obtain a reference to this element via the document.getElementById() method.

This code defines a variable (named map ) and assigns that variable to a new Map object. The function Map() is known as a constructor and its definition is shown below:

Constructor Description
Map(mapDiv:Node, opts?:MapOptions ) Creates a new map inside of the given HTML container — which is typically a DIV element — using any (optional) parameters that are passed.


  • All Maps JavaScript API requests must include an API key; we no longer support keyless access.
  • You must enable billing on each of your projects.

API Key and Billing Errors

Under certain circumstances, a darkened map, or 'negative' Street View image, watermarked with the text "for development purposes only", may be displayed. This behavior typically indicates issues with either an API key or billing. In order to use Google Maps Platform products, billing must be enabled on your account, and all requests must include a valid API key. The following flow will help troubleshoot this:

Are you using an API key?

I'm not sure. How can I check if I am using an API key?

An API key is passed as the key parameter in the URL that is used to load the Maps JavaScript API. Here are a few options to check if you are using an API key:

  • Use the Google Maps Platform API Checker Chrome extension. This allows you to determine if your website is properly implementing Google’s licensed Maps APIs.
  • If you are using a library or plugin to load the Maps JavaScript API, check the settings for that library and look for an API key option.
  • Check errors in your browser. If you see the following messages, you are not using your API key correctly:
    • Google Maps JavaScript API warning: NoApiKeys
    • Google Maps JavaScript API error: MissingKeyMapError

    For web developers:

    • If you have access to the source code of your application, look for the tag which is used to load the Maps JavaScript API. When loading the Maps JavaScript API, substitute YOUR_API_KEY in the code below with your API key.
    • Check the network traffic generated by your website in the browser. In Chrome, this can be viewed using the DevToolsNetwork tab. Here you will see the network requests made by your website. Requests made using the Maps JavaScript API will be under the path maps/api/js . Here you can confirm if the requests are using the key parameter. It may be helpful to filter your network traffic by maps/api/js when viewing the Network tab.

    No, I am not using an API key.

    To get an API key, click the button below. If you do not see a guided setup, follow the full instructions at Get Started with Google Maps Platform.
    Get Started

    Yes, I am using an API key.

    Great! Let’s move on and check if a billing account is attached to your project.

    Is a billing account attached to your project?

    I'm not sure. How can I check if billing account is attached to my project?

    Go to the Billing page in the Google Cloud Console and select the project under which your API key was created. To confirm the key is associated with the project:

    1. Go to the Credentials section, which can be accessed from the left side bar under Google Maps Platform > Credentials.
    2. Check that the API key you currently use on your website is listed. If that's not the case, switch to a different project, and check the credentials there.
    3. If you cannot locate the project for your API key, you may have lost access to this project. Ask others in your organization for help. If the original project cannot be located, you should:
      1. Create a new project. This can be done by selecting New Project from the projects list, or by selecting Create Project via the Resource Manager page.
      2. Create a new API key. This can be done on the Credentials page. Once there click Create credentials and then select API key.

      Once you have located your project in the Cloud Console, check if a billing account is attached by navigating to the Billing section in the left side menu.

      No, a billing account is not attached to my project.

      Go to the Enable Billing page in the Cloud Console and add a billing account to your project. For additional information, see Get Started with Google Maps Platform.

      Yes, a billing account is attached to my project.

      Great! Let’s make sure the provided billing method is valid.

      Is the provided billing method no longer valid (for example an expired credit card)?

      Is there an exceeded self-imposed daily limit on the API?

      If you have set a daily limit on any of your APIs, which is common to prevent unexpected increases, you can resolve this by increasing your daily limit.

      1. Select a project if prompted.
      2. Select an API from the list, then click the Quotas tab.

      Does your API key have an IP addresses restriction?

      If your code isn't working:

      • Look for typos. Remember that JavaScript is a case-sensitive language.
      • Check the basics - some of the most common problems occur with the initial map creation. Such as:
        • Confirm that you've specified the zoom and center properties in your map options.
        • Ensure that you have declared a div element in which the map will appear on the screen.
        • Ensure that the div element for the map has a height. By default, div elements are created with a height of 0, and are therefore invisible.

        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.

        Задача для примера

        1. Вывести карту (надо же!)
        2. Задать город
        3. Переместить карту к городу
        4. Маркером указать адрес
        5. Добавить информации
        6. Вывести карту (надо же!)
        7. Сохранить маркер с иноформацией (при клике на него вывести ее)
        8. Избежать нагромождения (т.е. сделать кластеризацию) маркеров.

        Как делать?

        Ключ API

        Для работы нам понадобится 3 основных объекта. Первое – это карта.
        Карта создается очень просто. У нас есть какой-то определенный контейнер:

        center: myLatlng – это координаты центра карты
        zoom – это увеличение при инициализации
        mapTypeId – тип (политическая, физическая, гибрид)
        Карта готова!

        Второе — это метки:

        position – собственно координаты метки
        map – на какую карту метку поместить
        title – при наведении мыши будет писать “Hello World!”.


        content – содержимое в метке

        — при клике на метку, показать окно с информацией, на карте map с привязкой к marker.

        • По наименованию чего-то, найти это на карте и сообщить координаты
        • По координатам, сообщить всё что находится на этих координатах.

        И в ответе приходит:

        Вся прелесть в том, что можно в address параметре передавать значение на любом языке(Ivanovo, Іваново, ), еще лучше, что для Санкт-Петербурга прокатывает «Спб» и «Питер». Правда есть и недочеты: мой родной город Ивано-Франковск упорно называет Ивано-Франковськ, на украинский манер.
        Вторая возможность, это по координатам узнать адрес:

        А теперь о не очень хорошем. Geocoder – насколько клевая функция, что пользоваться ею можно только 2500 запросов в день. Google предлагает Google API Key Premier от 10000$ в год, и тогда ограничение будет в 100 тыс. запросов в день, причем куча всяких «клевых» дополнений, но я их не могу себе позволить.


        Составляем массив маркеров, не добавляя в карту:

        maxZoom – максимальный зум при котором мы еще группируем маркеры, дальше – уже нет.
        gridSize – размер ячеек сетки, чем меньше значение, тем меньше сетка группировки
        styles – дополнительные стили

        Код из примера
        • собственно страница
        • получить все маркеры (в json)
        • загрузить файл (через ajaxUploader) и получить ссылку для картинки
        • сохранить в базу данных маркер (на выходе json result = ok)

        Функция для «прыжка» маркера:


        Google Maps API – очень классная и удобная штука, которая легка в использовании и понимании. Единственно, что плохо – так это слабое покрытие регионов в России, так что сервисам, которые предполагается использовать в глубинке google.maps пока мало интересен, а вот для больших городов (особенно Москва и Питер), а также для Украины – всё отлично.
        Geocoding – очень полезная вещь и при правильном использовании может стоить тех денег, что за нее просят (ну или Microsoft или Яндекс подоспеет с аналогом уже есть. Хотя насколько я знаю, картографическая информация стоит бешеных вложений.)

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