r1zen / react-yandex-maps Goto Github PK
View Code? Open in Web Editor NEWYandex.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
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
Есть ли у свойства, поддерживающие редактирование? В API Яндекса существует возможность настраивать точки с помощью которых можно редактировать линию прямо на карте, а так же есть пример как с этим работать. Тут я этого не обнаружил, но мне кажется оно должно поддерживаться и я просто не могу найти
Не нашел в документации получения longitude и latitude при действии onclick
В поле data
не хватает image
, context
поля по типам.
В рантайме всё работает отлично
Откуда нужно добавлять типы для корректной работы 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();
но в реакте не знаю как этот флоу описать
скрипт апи карты в первый раз грузился (если не загружен) перед открытием модалки (если читать вашу доку скрипт начинает грузится когда во вьюпорте карта появляется, в случае с модалкой это должно как-то аналогичным образом хендлиться)
Добавить поддержку react версий 17-18
Как отключить скролл карты по колесику мыши или touch скроллу в мобилке?
Начинает мешать при скролле элементов на странице, когда попадаются карты
Цели:
@types/yandex-maps
;prop-types
из сборки;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)
Warning: Unknown: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.
Стоит ли ждать обновления?)
Имеется несколько десятков меток, которые объединяются в кластеры. По клику на кластер необходимо получить именно те метки, которые в него сложены (для того, чтобы отрисовать данные об объектах в отдельном списке. Способ с переделкой балуна не подходит). Как передать данные в метки я уже понял, но не могу никак вычленить метки из кластера, по которому произошёл клик
Контекст
При использовании кнопки определения геолокации на карте, библиотека идет по адресу:
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')), но меняет сразу все кластеры.
Подскажите пожалуйста метод.
Как подписаться на события изменения карты?
к примеру на это событие? https://yandex.ru/dev/maps/jsapi/doc/2.1/ref/reference/Map.html#event_detail__event_detail/event-boundschange
Подскажите как в данном пакете работы с Яндекс Картами можно проложить маршруты между точками?
Передаю в кластер массив меток. Из 6 штук на карте отображается 5. Хотя в дереве элементов DevTools есть все 6, но одна из них не распознается. Пробовала добавлять "фейковую метку", но при изменении маштаба карты построение сбивается и снова возвращает неверные метки.
Карта расположена на сайте https://portland.forma.ru/infrastructure , можете отфильтровать метки парков и посмотреть, сколько элементов есть в DOM дереве, а сколько на карте. Всегда из массива удаляется именно первая метка.
При 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 свойства для 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
Добрый день, столкнулся с проблемой использования pbe/react-yandex-maps в NextJS проекте.
Использую Ymaps провайдер для доступа к виджету по всему приложению.
Виджет корректно отображается во время разработки, но как только речь доходит до продакшена, в консоле выводиться ошибка "Invalid API key"
Возможно ли узнать в чем может быть проблема?
Может быть мне необходимо расширить конфиг использования карты? Или быть может проблема может быть вовсе на стороне Yandex?
Буду благодарен за любую помощь! Если необходимо больше информации - прошу писать в комментарии. Спасибо!
Будет ли библиотека обновляться до 18го реакта?
Добрый день. Подскажите, можно ли как-то получить координаты метки после того как ее перестали перетаскивать?
Не нашел куда необходимо добавлять ключ который получил в кабинета разработчика?
Добрый день, есть ли возможность добавлять кастомные контролы по типу таких?
https://yandex.ru/dev/maps/jsbox/2.1/custom_control
@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
Попытки вытащить типизацию из библиотеки ни к чему не приводят, может я чего не заметил, но и в доке не нашел. Буду признателен за объяснение или дополнение )
Подскажите, пожалуйста, как включить темную тему для react/javascript? В официальной документации яндекс карт описывается такая возможность только для yandex map kit.
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
Hello!
Is it possible to get map instance through withYMaps
hook that was created in other component with useYMaps
?
При вводе текста в строку получаю сообщения в консоли Feature removed. Suggest is not available. See https://yandex.com/dev/jsapi-v2-1/doc/en/v2-1/ref/reference/suggest
<SearchControl options={{float: 'right'}}/>
Но после нажатия на Enter подсказки от Яндекса появляются. Проблема в том, что они не появляются при вводе и они вызывают такие ошибки при изменении текста в этом поле
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:
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
<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, подскажите что делаю не так?
При использовании geoObject
и при динамическом изменении набора объектов некоторые метки не отображаются на карте, хотя находятся в инстансе geoObject
-а.
Закинул пример в репозиторий
https://github.com/tilvan/yandex-map-example
Для воспроизведения нужно покликать кнопку сверху.
На карте должна оставаться одна метка.
Центр карты смещается как надо, но сама метка не отображается до тех пор, пока не изменю зум карты туда-сюда.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.