Cartesian projection graphics

Open in CodeSandbox

<!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">
      import {HEART_FEATURE, LOCATION, MAP_PARAMS, MAX, generateGrid} from './common';

      window.map = null;

      main();
      async function main() {
        // Waiting for all api elements to be loaded
        await ymaps3.ready;
        const {YMap, YMapDefaultFeaturesLayer, YMapFeature, YMapMarker, YMapControls} = ymaps3;

        const {YMapZoomControl} = await ymaps3.import('@yandex/ymaps3-default-ui-theme');
        const {Cartesian} = await ymaps3.import('@yandex/ymaps3-cartesian-projection');

        map = new YMap(document.getElementById('app'), {
          location: LOCATION,
          mode: 'raster',
          projection: new Cartesian([
            [-MAX, -MAX],
            [MAX, MAX]
          ]),
          ...MAP_PARAMS
        });

        map.addChild(new YMapDefaultFeaturesLayer({}));
        const {features, markers} = generateGrid();

        features.forEach((props) => {
          map.addChild(new YMapFeature(props));
        });

        markers.forEach(([props, element]) => {
          map.addChild(new YMapMarker(props, element));
        });

        map.addChild(new YMapFeature(HEART_FEATURE));

        map.addChild(new YMapControls({position: 'right'}).addChild(new YMapZoomControl({})));
      }
    </script>

    <!-- 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>
    <link rel="stylesheet" href="./common.css" />
  </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="react, typescript"
      type="text/babel"
      src="./common.ts"
    ></script>
    <script data-plugins="transform-modules-umd" data-presets="react, typescript" type="text/babel">
      import {HEART_FEATURE, LOCATION, MAP_PARAMS, MAX, generateGrid} 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, YMapDefaultFeaturesLayer, YMapFeature, YMapMarker, YMapControls} = reactify.module(ymaps3);

        const {YMapZoomControl} = reactify.module(await ymaps3.import('@yandex/ymaps3-default-ui-theme'));
        const {Cartesian} = await ymaps3.import('@yandex/ymaps3-cartesian-projection');
        const projection = new Cartesian([
          [-MAX, -MAX],
          [MAX, MAX]
        ]);

        const grid = generateGrid();

        function App() {
          return (
            // Initialize the map and pass initialization parameters
            <YMap location={LOCATION} projection={projection} {...MAP_PARAMS} ref={(x) => (map = x)}>
              <YMapDefaultFeaturesLayer />
              {grid.features.map((props) => (
                <YMapFeature {...props} />
              ))}
              {grid.markers.map(([props, element]) => (
                <YMapMarker {...props} markerElement={element} />
              ))}

              <YMapFeature {...HEART_FEATURE} />

              <YMapControls position="right">
                <YMapZoomControl />
              </YMapControls>
            </YMap>
          );
        }

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

    <!-- 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>
    <link rel="stylesheet" href="./common.css" />
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
.grid-marker {
  --offset: 8px;

  font-family: Helvetica, Arial, sans-serif;
  font-size: 24px;
  font-weight: 200;
  width: max-content;
  position: relative;
  display: flex;

  &.grid-marker_negative_true:before {
    content: '–';
    position: absolute;
    top: 0;
    display: block;
    height: 100%;
    margin-top: -2px;
    margin-left: -0.5em;
  }

  &.grid-marker_vertical_false {
    margin-top: var(--offset);

    transform: translateX(-50%);
  }

  &.grid-marker_vertical_true {
    margin-left: var(--offset);

    transform: translateY(-50%);

    &.grid-marker_negative_true:before {
      position: static;
      margin-top: -1px;
      margin-left: 0;
    }
  }

  &.grid-marker_center_true {
    margin-left: var(--offset);

    transform: none;
  }
}
import type {LngLat, YMapFeatureProps, YMapLocationRequest, YMapMarkerProps, YMapProps} from '@yandex/ymaps3-types';

export const MAX = 40;
export const LOCATION: YMapLocationRequest = {center: [0, 0], zoom: 1.7};
export const MAP_PARAMS: Partial<YMapProps> = {
  zoomRange: {min: 1.4, max: 5},
  zoomRounding: 'smooth'
};

const heartCoords: LngLat[] = [];

for (let t = 0; t <= 2 * Math.PI; t += 1e-5) {
  const x = 16 * Math.pow(Math.sin(t), 3);
  const y = 13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t);
  heartCoords.push([x, y]);
}

export const HEART_FEATURE = {
  geometry: {
    type: 'LineString' as const,
    coordinates: heartCoords
  },
  style: {
    stroke: [{color: '#34d9a2', width: 4}],
    simplificationRate: 0,
    zIndex: 1000
  }
};

interface Grid {
  features: YMapFeatureProps[];
  markers: [YMapMarkerProps, HTMLElement][];
}
export function generateGrid(): Grid {
  const features: Grid['features'] = [];
  const markers: Grid['markers'] = [];

  for (let i = -MAX; i < MAX; i++) {
    const style = {
      stroke: [
        {
          color: i === 0 ? '#000' : '#eee',
          width: i === 0 ? 2 : 1
        }
      ],
      zIndex: i === 0 ? 100 : 0
    };

    features.push({
      geometry: {
        type: 'LineString',
        coordinates: [
          [-MAX, i],
          [MAX, i]
        ]
      },
      style
    });

    features.push({
      geometry: {
        type: 'LineString',
        coordinates: [
          [i, -MAX],
          [i, MAX]
        ]
      },
      style
    });

    if (i % 10 === 0 && Math.abs(i) !== MAX) {
      const xMarker = document.createElement('div');
      xMarker.classList.add('grid-marker', 'grid-marker_vertical_false', 'grid-marker_negative_' + (i < 0));
      xMarker.innerText = String(Math.abs(i));
      markers.push([{coordinates: [i, 0]}, xMarker]);

      if (i !== 0) {
        const yMarker = document.createElement('div');
        yMarker.classList.add('grid-marker', 'grid-marker_vertical_true', 'grid-marker_negative_' + (i < 0));
        yMarker.innerText = String(Math.abs(i));
        markers.push([{coordinates: [0, i]}, yMarker]);
      } else {
        xMarker.classList.add('grid-marker', 'grid-marker_center_true');
      }
    }
  }

  return {features, markers};
}

declare module '@yandex/ymaps3-types/import' {
  interface Import {
    (pkg: '@yandex/ymaps3-cartesian-projection'): Promise<typeof import('@yandex/ymaps3-cartesian-projection')>;
  }
}

ymaps3.ready.then(() => {
  ymaps3.import.registerCdn('https://cdn.jsdelivr.net/npm/{package}', [
    '@yandex/ymaps3-default-ui-theme@0.0',
    '@yandex/ymaps3-cartesian-projection@0.0'
  ]);
});