gribnoysup / react-yandex-maps

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

Не работает setBounds() #262

Closed eugene-rn closed 3 years ago

eugene-rn commented 3 years ago

Здравствуйте! Мне нужно отрисовать карту так, чтобы сразу были видны все точки. Для этого использую ref.setBounds(ref.geoObjects.getBounds());, но что-то идет не так. Подскажите, пожалуйста, как правильно реализовать задачу.

Код:

<YMaps>
      <Map
        defaultState={{
          center: [55.75, 37.57],
          zoom: 9,
        }}
        width="100%"
        height={350}
        instanceRef={(ref): void => {
          if (ref) {
            ref.behaviors.disable('scrollZoom');
            ref.setBounds(ref.geoObjects.getBounds());
          }
        }}
      >
        {marks.map((event: IPathItem) => (
          <Placemark
            key={uniqueId()}
            defaultGeometry={[Number(event.latitude), Number(event.longitude)]}
          />
        ))}

        <ZoomControl options={{ float: 'right' }} />
      </Map>
    </YMaps>

Получаю следующую ошибку и краш страницы:

Снимок экрана 2020-09-24 в 21 50 55
mmarkelov commented 3 years ago

@DarrenClyde привет! Я думаю, что проблема в том, что на момент получения ссылки на карту, в нее еще не добавлены. Предполагаю что у Вас есть массив точек с координатами, поэтому можно использовать метод ymaps.util.bounds.fromPoints(points) в качестве данных ожидается массив координат https://yandex.ru/dev/maps/jsapi/doc/2.1/ref/reference/util.bounds-docpage/

      useEffect(() => {
        if (mapRef.current) {
          mapRef.current.setBounds(bounds);
        }
      }, [bounds]); 

       <Map
          modules={["util.bounds"]}
          onLoad={(ymaps) => {
            const points = [
              [55.984758, 39.938521],
              [55.684758, 37.738521]
            ];
            setBounds(ymaps.util.bounds.fromPoints(points));
          }}
          state={mapState}
          instanceRef={(ref) => {
            if (ref) {
              mapRef.current = ref;
            }
          }}   
        />
eugene-rn commented 3 years ago

@mmarkelov Благодарю! Ваше решение помогло)