Creating maps on demand

Open in CodeSandbox

In this example, the map is created when the "Show map" button is clicked.

At first, an empty div container is placed on the page. The bind() function is used for the "button" element to assign a handler for the click event, which creates the map and puts it in the specified container when called.

If the map has already been created when the button is clicked, the destroy() method is called and it destroys the map.

  <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Examples. Creating maps on demand.</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <!--
            Set your own API-key. Testing key is not valid for other web-sites and services.
            Get your API-key on the Developer Dashboard: https://developer.tech.yandex.ru/keys/
        -->
        <script src="https://api-maps.yandex.ru/2.1/?lang=en_RU&amp;apikey=<your API-key>" type="text/javascript"></script>
        <!--
            Enabling JQuery.
            Yandex provides hosting of JavaScript libraries:
        -->
        <script src="https://yandex.st/jquery/2.2.3/jquery.min.js" type="text/javascript"></script>
        <script src="request_map.js" type="text/javascript"></script>
    </head>

    <body>
        <input type="button" value="Show map" id="toggle"/>
        <p>
            <div id="map" style="width: 400px; height: 300px"></div>
        </p>
    </body>
</html>
// As soon as the API is loaded and DOM is ready, let's perform the initialization
ymaps.ready(init);

// Initialization and destruction of the map when the button is clicked.
function init() {
    var myMap;

    $("#toggle").bind({
        click: function () {
            if (!myMap) {
                myMap = new ymaps.Map(
                    "map",
                    {
                        center: [55.010251, 82.958437], // Novosibirsk
                        zoom: 9,
                    },
                    {
                        searchControlProvider: "yandex#search",
                    }
                );
                $("#toggle").attr("value", "Hide map");
            } else {
                myMap.destroy(); // Destructor of the map
                myMap = null;
                $("#toggle").attr("value", "Show the map again");
            }
        },
    });
}