Adding traffic jams layer to the map

Open in CodeSandbox

Alert

To show traffic or traffic events, add YMapTrafficLayer or YMapTrafficEventsLayer layers to the map. Access to these layers is provided on paid tariffs.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
    <script crossorigin src="https://cdn.jsdelivr.net/npm/@babel/standalone@7/babel.min.js"></script>
    <!-- To make the map appear, you must add your apikey -->
    <script src="https://api-maps.yandex.ru/v3/?apikey=<YOUR_APIKEY>&lang=en_US" type="text/javascript"></script>

    <script
      data-plugins="transform-modules-umd"
      data-presets="typescript"
      type="text/babel"
      src="./common.ts"
    ></script>
    <script
      data-plugins="transform-modules-umd"
      data-presets="typescript"
      type="text/babel"
      src="../variables.ts"
    ></script>
    <script data-plugins="transform-modules-umd" data-presets="typescript" type="text/babel">
      import {LOCATION} from '../variables';
      import {showTrf, showTrfe} from './common';
      window.map = null;

      main();
      async function main() {
        // Waiting for all api elements to be loaded
        await ymaps3.ready;
        const {YMap, YMapDefaultSchemeLayer, YMapControlButton, YMapControls} = ymaps3;
        const {YMapTrafficLayer, YMapTrafficEventsLayer} = await ymaps3.import('@yandex/ymaps3-layers-extra');

        // Initialize the map
        map = new YMap(
          // Pass the link to the HTMLElement of the container
          document.getElementById('app'),
          // Pass the map initialization parameters
          {location: LOCATION, showScaleInCopyrights: true},
          // Add a map scheme layer
          [new YMapDefaultSchemeLayer({})]
        );
        let showTraffic = showTrf;
        let showTrafficEvents = showTrfe;
        const trafficLayer = new YMapTrafficLayer({visible: showTraffic});
        const trafficEventsLayer = new YMapTrafficEventsLayer({visible: showTrafficEvents});

        const trfSign = document.createElement('div');
        trfSign.innerText = '🚥';
        trfSign.classList.add('btn');

        const trfEventSign = document.createElement('div');
        trfEventSign.innerText = '🚧';
        trfEventSign.classList.add('btn');

        const toggleTraffic = new YMapControlButton({
          element: trfSign,
          onClick: () => {
            showTraffic = !showTraffic;
            trafficLayer.update({visible: showTraffic});
          }
        });
        const toggleTrafficEvents = new YMapControlButton({
          element: trfEventSign,
          onClick: () => {
            showTrafficEvents = !showTrafficEvents;
            trafficEventsLayer.update({visible: showTrafficEvents});
          }
        });

        map.addChild(new YMapControls({position: 'top'}, [toggleTraffic, toggleTrafficEvents]));
        map.addChild(trafficLayer);
        map.addChild(trafficEventsLayer);
      }
    </script>

    <link rel="stylesheet" href="./common.css" />
    <!-- prettier-ignore -->
    <style> html, body, #app { width: 100%; height: 100%; margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } .toolbar { position: absolute; z-index: 1000; top: 0; left: 0; display: flex; align-items: center; padding: 16px; } .toolbar a { padding: 16px; }  </style>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
    <script crossorigin src="https://cdn.jsdelivr.net/npm/react@17/umd/react.production.min.js"></script>
    <script crossorigin src="https://cdn.jsdelivr.net/npm/react-dom@17/umd/react-dom.production.min.js"></script>
    <script crossorigin src="https://cdn.jsdelivr.net/npm/@babel/standalone@7/babel.min.js"></script>
    <!-- To make the map appear, you must add your apikey -->
    <script src="https://api-maps.yandex.ru/v3/?apikey=<YOUR_APIKEY>&lang=en_US" type="text/javascript"></script>

    <script
      data-plugins="transform-modules-umd"
      data-presets="typescript"
      type="text/babel"
      src="./common.ts"
    ></script>
    <script
      data-plugins="transform-modules-umd"
      data-presets="typescript"
      type="text/babel"
      src="../variables.ts"
    ></script>
    <script data-plugins="transform-modules-umd" data-presets="react, typescript" type="text/babel">
      import {LOCATION} from '../variables';
      import {showTrf, showTrfe} from './common';
      window.map = null;

      main();
      async function main() {
        // For each object in the JS API, there is a React counterpart
        // To use the React version of the API, include the module @yandex/ymaps3-reactify
        const [ymaps3React] = await Promise.all([ymaps3.import('@yandex/ymaps3-reactify'), ymaps3.ready]);
        const reactify = ymaps3React.reactify.bindTo(React, ReactDOM);
        const {YMap, YMapDefaultSchemeLayer, YMapControls, YMapControlButton} = reactify.module(ymaps3);
        const {YMapTrafficLayer, YMapTrafficEventsLayer} = reactify.module(
          await ymaps3.import('@yandex/ymaps3-layers-extra')
        );
        const {useState} = React;

        function App() {
          const [location, setLocation] = useState(LOCATION);
          const [showTraffic, setShowTraffic] = useState(showTrf);
          const [showTrafficEvents, setShowTrafficEvents] = useState(showTrfe);

          return (
            // Initialize the map and pass initialization parameters
            <YMap location={location} showScaleInCopyrights={true} ref={(x) => (map = x)}>
              {/* Add a map scheme layer */}
              <YMapDefaultSchemeLayer />
              <YMapTrafficLayer visible={showTraffic} />
              <YMapTrafficEventsLayer visible={showTrafficEvents} />
              <YMapControls position="top">
                <YMapControlButton onClick={() => setShowTraffic((prev) => !prev)}>
                  <span className="btn">🚥</span>
                </YMapControlButton>
                <YMapControlButton onClick={() => setShowTrafficEvents((prev) => !prev)}>
                  <span className="btn">🚧</span>
                </YMapControlButton>
              </YMapControls>
            </YMap>
          );
        }

        ReactDOM.render(
          <React.StrictMode>
            <App />
          </React.StrictMode>,
          document.getElementById('app')
        );
      }
    </script>

    <link rel="stylesheet" href="./common.css" />
    <!-- prettier-ignore -->
    <style> html, body, #app { width: 100%; height: 100%; margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } .toolbar { position: absolute; z-index: 1000; top: 0; left: 0; display: flex; align-items: center; padding: 16px; } .toolbar a { padding: 16px; }  </style>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
    <script crossorigin src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.js"></script>
    <script crossorigin src="https://cdn.jsdelivr.net/npm/@babel/standalone@7/babel.min.js"></script>

    <script src="https://api-maps.yandex.ru/v3/?apikey=<YOUR_APIKEY>&lang=en_US" type="text/javascript"></script>

    <script
      data-plugins="transform-modules-umd"
      data-presets="typescript"
      type="text/babel"
      src="./common.ts"
    ></script>
    <script
      data-plugins="transform-modules-umd"
      data-presets="typescript"
      type="text/babel"
      src="../variables.ts"
    ></script>
    <script data-plugins="transform-modules-umd" data-presets="typescript" type="text/babel">
      import {LOCATION} from '../variables';
      import {showTrf, showTrfe} from './common';

      window.map = null;

      async function main() {
        // For each object in the JS API, there is a Vue counterpart
        // To use the Vue version of the API, include the module @yandex/ymaps3-vuefy
        const [ymaps3Vue] = await Promise.all([ymaps3.import('@yandex/ymaps3-vuefy'), ymaps3.ready]);
        const vuefy = ymaps3Vue.vuefy.bindTo(Vue);
        const {YMap, YMapDefaultSchemeLayer, YMapControls, YMapControlButton} = vuefy.module(ymaps3);
        const {YMapTrafficLayer, YMapTrafficEventsLayer} = vuefy.module(
          await ymaps3.import('@yandex/ymaps3-layers-extra')
        );

        const app = Vue.createApp({
          components: {
            YMap,
            YMapDefaultSchemeLayer,
            YMapControls,
            YMapControlButton,
            YMapTrafficEventsLayer,
            YMapTrafficLayer
          },
          setup() {
            const refMap = (ref) => {
              window.map = ref?.entity;
            };
            const showTraffic = Vue.ref(showTrf);
            const showTrafficEvents = Vue.ref(showTrfe);
            const toggleTraffic = () => {
              showTraffic.value = !showTraffic.value;
            };
            const toggleTrafficEvents = () => {
              showTrafficEvents.value = !showTrafficEvents.value;
            };
            return {LOCATION, refMap, showTraffic, showTrafficEvents, toggleTraffic, toggleTrafficEvents};
          },
          template: `
            <YMap :location="LOCATION" :showScaleInCopyrights="true" :ref="refMap">
                <YMapDefaultSchemeLayer />
                <YMapTrafficLayer :visible="showTraffic" />
                <YMapTrafficEventsLayer :visible="showTrafficEvents" />
                <YMapControls position="top">
                    <YMapControlButton :onClick="toggleTraffic">
                        <span class='btn'>🚥</span>
                    </YMapControlButton>
                    <YMapControlButton :onClick="toggleTrafficEvents">
                        <span class='btn'>🚧</span>
                    </YMapControlButton>
                </YMapControls>
            </YMap>`
        });
        app.mount('#app');
      }
      main();
    </script>

    <link rel="stylesheet" href="./common.css" />
    <!-- prettier-ignore -->
    <style> html, body, #app { width: 100%; height: 100%; margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } .toolbar { position: absolute; z-index: 1000; top: 0; left: 0; display: flex; align-items: center; padding: 16px; } .toolbar a { padding: 16px; }  </style>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
.btn {
  font-size: 20px;
}
export const showTrf = true;
export const showTrfe = true;
import type {YMapLocationRequest} from '@yandex/ymaps3-types';

export const LOCATION: YMapLocationRequest = {
  center: [37.623082, 55.75254], // starting position [lng, lat]
  zoom: 12 // starting zoom
};