J
J
Juniorrrrr2021-01-26 13:31:43
Yandex maps
Juniorrrrr, 2021-01-26 13:31:43

How to correctly set points on a Yandex map with Reactjs?

Hello everyone. I'm trying to initialize the Yandex map, and when I click on the button, I set the point.

Setting the point takes a long time, the card becomes unusable, stops responding to the mouse.

Please tell me what am I doing wrong?

An example can be viewed here

export default function App() {
  const [isLoaded, setIsLoaded] = React.useState(false);
  const [map, setMap] = React.useState(null);

  function fetchScript(url) {
    return new Promise((resolve, reject) => {
      this.script = document.createElement("script");

      this.script.type = "text/javascript";
      this.script.onload = resolve;
      this.script.onerror = reject;
      this.script.src = `https://api-maps.yandex.ru/2.1/?apikey=86f5784f-3442-4cdf-8c42-205d3c76e368&lang=ru_RU`;
      this.script.async = "async";

      document.head.appendChild(this.script);
    });
  }

  // загрузка скрипта
  React.useEffect(() => {
    fetchScript().then(() => setIsLoaded(true));
  }, []);

  const createMap = () => {
    try {
      ymaps.ready(() => {
        const newMap = new ymaps.Map(
          "customMap",
          { center: [55.76, 37.64], zoom: 9 },
          {
            searchControlProvider: "yandex#search"
          }
        );
        setMap(newMap);
      });
    } catch (error) {
      console.log("error is", error);
    }
  };

  // если скрипт карты подключен, инициализировать карту
  React.useEffect(() => {
    if (isLoaded && !map) {
      createMap();
    }
  }, [isLoaded, map]);

  let counter = 0.1;

  return (
    <>
      <div id="customMap" style={{ height: 300 }}>
        Here will be a map
      </div>

      <button
        style={{ marginTop: 150 }}
        onClick={() => {
          console.log("ymaps", ymaps);
          counter = counter + 0.1;

          var myGeoObject = new ymaps.GeoObject({
            geometry: {
              type: "Point", // тип геометрии - точка
              coordinates: [55.8, 37.07 + counter] // координаты точки
            }
          });

          // Размещение геообъекта на карте.
          map.geoObjects.add(myGeoObject);
        }}
      >
        Create Point
      </button>
    </>
  );
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Pastukhov, 2021-01-26
@Juniorrrrr

It's not your code that slows down, but codesandbox - it tries to process - due to the fact that ymaps is very large and its own implementation of the console Replace withconsole.log("ymaps", ymaps);
console.log("ymaps", !!ymaps);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question