Giter Site home page Giter Site logo

r1zen / react-yandex-maps Goto Github PK

View Code? Open in Web Editor NEW
113.0 113.0 19.0 2.06 MB

Yandex.Maps API bindings for React (fork https://github.com/gribnoysup/react-yandex-maps)

Home Page: https://pbe-react-yandex-maps.vercel.app

License: MIT License

JavaScript 2.29% TypeScript 59.44% CSS 0.58% MDX 37.69%
react react-yandex-maps yandex-maps yandex-maps-api ymaps

react-yandex-maps's People

Contributors

armanio avatar dhffdh avatar evgenii-minkov avatar koderfunk avatar owtmpatrick avatar r1zen avatar semro avatar thavguard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

react-yandex-maps's Issues

Редактирование <Polyline/>

Есть ли у свойства, поддерживающие редактирование? В API Яндекса существует возможность настраивать точки с помощью которых можно редактировать линию прямо на карте, а так же есть пример как с этим работать. Тут я этого не обнаружил, но мне кажется оно должно поддерживаться и я просто не могу найти

Как правильно использовать с typescript

Откуда нужно добавлять типы для корректной работы ts.

Пример:

const [currentMap, setCurrentMap] = useState<YMapsApi | null>(null);

useEffect(() => {
    // ESLint: Unsafe member access .getBounds on an `any` value.(@typescript-eslint/no-unsafe-member-access)
    if (!currentMap?.geoObjects.getBounds()) {
      return;
    }
    // ESLint: Unsafe member access .getBounds on an `any` value.
    currentMap.setBounds(currentMap.geoObjects.getBounds(), { zoomMargin: 20 });
  }, [currentMap]);

Если посмотреть в типы:

interface AnyObject {
  [key: string]: any;
}

export interface YMapsApi extends AnyObject {}

Такая же проблема будет если будем делать что-то делать с элементами управления:

<SearchControl
              instanceRef={(ref) => {
                setSearchControl(ref);
              }}
>
// ESLint: Unsafe member access .getResultsArray on an `any` value.
const results = searchControl.getResultsArray();

Можно как-то подружить с - https://www.npmjs.com/package/@types/yandex-maps?
Или есть какие-то другие решения?

Обновился до последней версии - пропали типы

Помогите отрефакторить компонент с новой версией

import { memo } from 'react';
import type { PlacemarkGeometry, MapProps } from '@pbe/react-yandex-maps';
import { Map, Placemark } from '@pbe/react-yandex-maps';


interface YandexPlaceMark {
  geometry: PlacemarkGeometry;
  hintContent?: string;
}

interface YandexMapProps extends MapProps {
  center: PlacemarkGeometry;
  zoom: number;
  placeMarks: YandexPlaceMark[];
  className?: string;
}

const YandexMap = memo((props: YandexMapProps) => {
  const { center, zoom, placeMarks, className, ...rest } = props;
  return (
    <Map
      width="100%"
      height="100%"
      modules={[
        'control.ZoomControl',
        'control.FullscreenControl',
        'geoObject.addon.balloon',
        'geoObject.addon.hint',
      ]}
      state={{
        center,
        controls: ['zoomControl', 'fullscreenControl'],
        zoom,
      }}
      className={className}
      {...rest}
    >
      {placeMarks.map(({ geometry, hintContent }: YandexPlaceMark, index: number) => (
        <Placemark
          // eslint-disable-next-line react/no-array-index-key
          key={index}
          geometry={geometry}
          properties={{
            hintContent,
          }}
          options={{
            iconColor: 'var(--primary)',
          }}
        />
      ))}
    </Map>
  );
});

YandexMap.displayName = 'YandexMap';

export type { YandexMapProps };
export { YandexMap };

Собственно PlacemarkGeometry, MapProps уже недоступны.

Размещение в скрытом контейнере

Доброго времени суток.
https://codesandbox.io/s/dank-fast-se8fej?file=/src/App.tsx

Кейс: на сайте в футере есть картинка со скрином карты и кнопка открывающая модалку с картой (в портале).
Подскажите как доработать код чтобы

  • карта получала актуальные значения контейнера после открытия модалки
    (гуглил, в нативном коде нужно делать что-то типо myMap.container.fitToViewport(); но в реакте не знаю как этот флоу описать

  • скрипт апи карты в первый раз грузился (если не загружен) перед открытием модалки (если читать вашу доку скрипт начинает грузится когда во вьюпорте карта появляется, в случае с модалкой это должно как-то аналогичным образом хендлиться)

!warn default props

image

Предупреждение по дефолтным пропсам, есть возможность обновить их объявление в коде?

image

Перейти на TypeScript

Цели:

  • Получить автогенерацию типов библиотеки из типов компонент;
  • Использовать поддерживающийся типы для ymaps: @types/yandex-maps;
  • Убрать prop-types из сборки;
  • Упростить дальнейший рефакторинг за счет статического анализа.

Ошибка при закрытии карты на react18

Warning: useEffect must not return anything besides a function, which is used for clean-up. You returned: [object Object]
at http://localhost:5173/node_modules/.vite/deps/@pbe_react-yandex-maps.js?v=b2e994ed:45:20

Uncaught TypeError: destroy is not a function
at safelyCallDestroy (react-dom.development.js:22932:5)
at commitHookEffectListUnmount (react-dom.development.js:23100:11)
at commitPassiveUnmountInsideDeletedTreeOnFiber (react-dom.development.js:25098:11)
at commitPassiveUnmountEffectsInsideOfDeletedTree_begin (react-dom.development.js:25048:5)
at commitPassiveUnmountEffects_begin (react-dom.development.js:24956:11)
at commitPassiveUnmountEffects (react-dom.development.js:24941:3)
at flushPassiveEffectsImpl (react-dom.development.js:27038:3)
at flushPassiveEffects (react-dom.development.js:26984:14)
at react-dom.development.js:26769:9
at workLoop (scheduler.development.js:266:34)

Defaultprops deprecated

Warning: Unknown: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.

Стоит ли ждать обновления?)

Получение объектов из кластера по клику

Имеется несколько десятков меток, которые объединяются в кластеры. По клику на кластер необходимо получить именно те метки, которые в него сложены (для того, чтобы отрисовать данные об объектах в отдельном списке. Способ с переделкой балуна не подходит). Как передать данные в метки я уже понял, но не могу никак вычленить метки из кластера, по которому произошёл клик

Не работает функционал геолокации, так как в запросах к API отсутствует заголовок Referer

Контекст
При использовании кнопки определения геолокации на карте, библиотека идет по адресу:
https://api-maps.yandex.ru/services/search/v2/
В этом запросе нужно прокидывать API-key, без него сервер будет отвечать 403

Проблема
С недавнего времени, в ЛК разработчика с API ключами указание ограничения по HTTP Referer является обязательным. Если пытаться делать запросы не проставив домены в ЛК - все запросы будут получать 403, даже если ключ правильный

Мы проставили домены в ЛК. но теперь все запросы получают 401 Unauthorized

Оговорка: ЛК Яндекса в явном виде предупреждает о том, что нужно проставить ограничение. Но у нас она появилась буквально пару недель назад, ощущение что пару недель назад такого не было (возможно это точечно на наш аккаунт, а возможно новые глобальные правила использования API)

Решение
В ходе дебага выяснил, что библиотека не передает заголовок "Referer" при отправке запроса в API. При этом API яндекса видимо использует данные этого заголовка для сверки с ограничениями. Если добавить руками поле Referer - все работает корректно

Можно ли добавить проброс этого поля?

Не могу делать свои версии компонентов и хуков

Нет экспорта деталей, вроде useYMapsApiLoader, в результате чего не могу спуститься на уровень библиотеки и модифицировать какую либо деталь, не могу повторить её в проекте из-за невозможности импорта составных функций (компонентов, хуков, utils).
Выглядит как нарушение open-closed из SOLID.

Как поменять по клику цвет кластера

Здравствуйте.
Как поменять по клику цвет кластера? Использую ObjectManager.
Пробовал через e.get("target").options.set("preset', 'islands#invertedVioletClusterIcons')), но меняет сразу все кластеры.
Подскажите пожалуйста метод.

Не отображает одну метку из кластера на карте

Передаю в кластер массив меток. Из 6 штук на карте отображается 5. Хотя в дереве элементов DevTools есть все 6, но одна из них не распознается. Пробовала добавлять "фейковую метку", но при изменении маштаба карты построение сбивается и снова возвращает неверные метки.

Карта расположена на сайте https://portland.forma.ru/infrastructure , можете отфильтровать метки парков и посмотреть, сколько элементов есть в DOM дереве, а сколько на карте. Всегда из массива удаляется именно первая метка.

Указание suggest options types

При ymaps.suggest(inputValue, { results: 5, types: 'locality'})

указанный types проигнорируется и в запросе будет указан 'geo'.

Единственное решение по изменению types на 'locality', которое я нашел, это в ручную отправлять запрос:
method: 'get',
url: https://suggest-maps.yandex.ru/v1/suggest,
params: {
apikey: yourKey,
text: inputValue,
results: 5,
types: 'locality',
}

Есть ли другие решения?

onLoad prop error

При использовании onLoad свойства для Map, выводит ошибку:
Warning: useEffect must not return anything besides a function, which is used for clean-up.

It looks like you wrote useEffect(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:

useEffect(() => {
async function fetchData() {
// You can await here
const response = await MyAPI.getData(someId);
// ...
}
fetchData();
}, [someId]); // Or [] if effect doesn't need props or state

Using react-yandex-maps in NextJS project

Добрый день, столкнулся с проблемой использования pbe/react-yandex-maps в NextJS проекте.

Использую Ymaps провайдер для доступа к виджету по всему приложению.

image

image

Виджет корректно отображается во время разработки, но как только речь доходит до продакшена, в консоле выводиться ошибка "Invalid API key"

image

Возможно ли узнать в чем может быть проблема?

Может быть мне необходимо расширить конфиг использования карты? Или быть может проблема может быть вовсе на стороне Yandex?

Буду благодарен за любую помощь! Если необходимо больше информации - прошу писать в комментарии. Спасибо!

Отключение информации от Яндекса при клике на объект

Есть ли какая-нибудь возможность отключить balloon после клика пользователем по Яндекс объекту на карте?

То есть, чтобы при клике на название сквера ничего не происходило. Пока это работает, если не указывать apikey, однако он мне нужен.

image

Remove defaultProps for React 18.3.0

@pbe/react-yandex-maps: 1.2.2
React Version: 18.2.0
Chrome

Problem
Warning: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.

Need to fix this before the release of react 18.3.0

Почему не доступны PropsType в связке с TS?

Попытки вытащить типизацию из библиотеки ни к чему не приводят, может я чего не заметил, но и в доке не нашел. Буду признателен за объяснение или дополнение )

Night Mode react/javascript

Подскажите, пожалуйста, как включить темную тему для react/javascript? В официальной документации яндекс карт описывается такая возможность только для yandex map kit.

License violation

By not including original license of the forked repository you are breaking MIT license conditions:

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

If you will not include the license I'll have to issue a DMCA takedown

Suggest is not available. See https://yandex.com/dev/jsapi-v2-1/doc/en/v2-1/ref/reference/suggest

При вводе текста в строку получаю сообщения в консоли Feature removed. Suggest is not available. See https://yandex.com/dev/jsapi-v2-1/doc/en/v2-1/ref/reference/suggest
Screenshot 2024-02-26 at 13 38 16

<SearchControl options={{float: 'right'}}/>

Но после нажатия на Enter подсказки от Яндекса появляются. Проблема в том, что они не появляются при вводе и они вызывают такие ошибки при изменении текста в этом поле

Placemark fails to render on subsequent mounts

I have a component with several tabs. Map is a part of one of them.

As I load the page, the map renders correctly, but if I switch the tabs back and forth, the placemark disappears, and the error message logs in the console: Uncaught TypeError: this._overlayClass is not a constructor

Here's the video with the issue:

Issue.video.mov

Simplified code of the part that switches:

{activeTab === 'building' && (
  <>
    ...
      <Map defaultState={{ center: [48.47854, 135.12157], zoom: 16 }}>
        <Placemark defaultGeometry={[48.47854, 135.12157]} />
      </Map>
    ...
  </>
}

showTab is a state variable needed to conditionally render the content of the tab, which changes when one of the buttons is clicked. Also I wrapped the whole app with <YMaps></YMaps> provider, so it is presented in the components tree as well.

After googling the error message I figured, that the issue might occur because of the Placemark component's attempt to render itself while the Map is not loaded yet.

Not sure, why it happens, because the first mount seems ok, but I think it could be enough to add some kind of a check for this condition somewhere, either in the Map component of in the child one.

Unfortunately, I have no experience with class components whatsoever, so my attempts of fixing it failed completely.

P.S. Haven't tried it, but by the looks of the code structure it seems that the same issue should be happening at least for every BaseGeoObject.

polygon.editor.startDrawing()

Не понятно как отредактировать текущий polygon

        <YMaps>
          <Map
            defaultState={{
              center: [55.73, 37.9],
              zoom: 10,
            }}
          >
            <Polygon
              instanceRef={(ref) => console.log(ref)}
              geometry={[
                [
                  [55.75, 37.8],
                  [55.8, 37.9],
                  [55.75, 38.0],
                  [55.7, 38.0],
                  [55.7, 37.8],
                ],
                [
                  [55.75, 37.82],
                  [55.75, 37.98],
                  [55.65, 37.9],
                ],
              ]}
              options={{
                cursor: 'crosshair',
                fillColor: '#00FF00',
                strokeColor: '#0000FF',
                opacity: 0.5,
                strokeWidth: 5,
                strokeStyle: 'shortdash',
              }}
            />
          </Map>
        </YMaps>

в объекте ref нет параметра editor, подскажите что делаю не так?

image

Некорректно отображаются метки при динамическом изменении набора объектов

При использовании geoObject и при динамическом изменении набора объектов некоторые метки не отображаются на карте, хотя находятся в инстансе geoObject-а.

Закинул пример в репозиторий
https://github.com/tilvan/yandex-map-example
Для воспроизведения нужно покликать кнопку сверху.
На карте должна оставаться одна метка.
Центр карты смещается как надо, но сама метка не отображается до тех пор, пока не изменю зум карты туда-сюда.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.