gribnoysup / react-yandex-maps

Yandex Maps API bindings for React
MIT License
327 stars 116 forks source link

Подключение карты без react-yandex-maps #220

Closed legiorex closed 4 years ago

legiorex commented 4 years ago

Как подключить карту без react-yandex-maps. Вопрос больше обучающий. Карту мне удается подключить, но вот доступ к глобальному объекту window.ymaps получить не удается.

export const initMap = (ref, center, zoom) => {

  const renderMap = () => {
    window.map = new ymaps.Map(ref, {
      center,
      zoom,
      controls: ['routePanelControl'],
    });
  };

  return loadScript(yandexMap, () => {
    return new Promise((resolve) => {
      resolve();
    }).then(() => window.ymaps.ready(renderMap), () => console.log('init Error'));

  });
};

const loadScript = (src, onLoad) => {
  const script = document.createElement('script');

  script.src = src;
  script.async = true;
  document.body.appendChild(script);
  script.onload = onLoad;

};

В браузере есть window.ymaps, но в компоненте доступа к нему нет.

mmarkelov commented 4 years ago

@legiorex нужно создавать карту в ymaps.init:

import React from "react";

const loadScript = (src, onLoad) => {
  const script = document.createElement("script");

  script.src = src;
  script.async = true;
  document.body.appendChild(script);
  script.onload = onLoad;
};

const init = () => {
  const myMap = new window.ymaps.Map("map", {
    // Координаты центра карты.
    // Порядок по умолчанию: «широта, долгота».
    // Чтобы не определять координаты центра карты вручную,
    // воспользуйтесь инструментом Определение координат.
    center: [55.76, 37.64],
    // Уровень масштабирования. Допустимые значения:
    // от 0 (весь мир) до 19.
    zoom: 7
  });
};

export default function App() {
  React.useEffect(() => {
    loadScript("https://api-maps.yandex.ru/2.1/?lang=ru_RU", () => {
      window.ymaps.ready(init);
    });
  }, []);

  return (
    <div className="App">
      <div id="map" style={{ width: 600, height: 400 }} />
    </div>
  );
}

Дока

legiorex commented 4 years ago

Большое спасибо. Я вроде бы разобрался с этим. Но еще одна проблемка. Создаю кнопку с функцией добавления маркера на карту, маркер создается, но он не двигается. Причем если вызывать api через библиотеку react-yandex-maps - этот код работает.

export const addPlacemark = (...arg) => {

  const [center, balloonContent, iconContent, index, iconColor] = arg;

  const { map, polyline } = window;

  ymaps.modules.require(['Placemark', 'overlay.Placemark']).spread((Placemark) => {

    ymaps.Placemark = Placemark;

    const placemark = new Placemark(

      center,
      {
        iconContent,
        balloonContent,
        index,
      },
      {
        draggable: true,
        iconColor,
      }
    );

    map.geoObjects.add(placemark, index);
    polyline.geometry.set(index, placemark.geometry.getCoordinates());

    placemark.geometry.events.add('change', (e) => {

      const indexOf = map.geoObjects.indexOf(placemark);

      const newCoords = e.get('newCoordinates');

      polyline.geometry.set(indexOf, newCoords);

    });

  });

};

Опция draggable: true есть, остальные свойства, которые я добавляю - цвет маркера, тайтл маркера - всё добавляется. Но он не двигается мышью. Если же этот код добавить при инициализации карты, то маркер двигается.

mmarkelov commented 4 years ago

@legiorex вам нужно сохранять ссылку на созданную карту. Либо через реакт реф, либо в window:

window.map = new window.ymaps.Map("map", ...);

// Тогда 
const { map, polyline } = window;

либо

const map = React.createRef();

map.current = new window.ymaps.Map("map", ...);
legiorex commented 4 years ago

Я использую первый вариант.

legiorex commented 4 years ago

Извините, всё работает. Надо разобраться, почему в моем коде оно не работало.