TypeError: Cannot read properties of undefined (reading 'createClass') react yandex map

Рейтинг: 0Ответов: 0Опубликовано: 18.05.2023

Пытаюсь создать карту в которой можно было бы добавлять маркера, помимо этого я так же хочу реализовать собственный балун для маркера. Нашел в документация, что это можно сделать через

ymaps.templateLayoutFactory.createClass

Попытался это интегрировать в свой код, но получаю ошибку undefined (reading 'createClass'). Решил в гите поискать реализацию моих мдей, наткнулся на Репозиторий в гите. Скачал запустил, работает. Решил просто в тупую скопировать его код в свой компонент, но так же получаю эту ошибку. Буду рад любой подсказке. Спасибо!

PS Прошу не обращать внимание на множественные модули, я вырезал лишний код, чтобы не засорять вопрос.

import { YMaps, Map , Button } from '@pbe/react-yandex-maps';
const mapState = {
    center: [55.7924886417031, 49.12233672582469],
    zoom: 9
};

const YMap = () => {
    const ymaps = React.useRef(null);
    
    const placemarkRef = React.useRef(null);
    const mapRef = React.useRef(null);

    const createPlacemark = (coords) => {
        return new ymaps.Placemark(
            coords,
            {
                iconCaption: "loading.."
            },
            {
                preset: "islands#violetDotIconWithCaption",
                draggable: true
            }
        );
    };
    let regionName = "";
    const getAddress =  (coords) => {
        placemarkRef.properties.set("iconCaption", "loading..");
        ymaps.current.geocode(coords).then((res) => {
                const firstGeoObject = res.geoObjects.get(0);
                const newAddress = [
                    firstGeoObject.getLocalities().length
                        ? firstGeoObject.getLocalities()
                        : firstGeoObject.getAdministrativeAreas(),
                    firstGeoObject.getThoroughfare() || firstGeoObject.getPremise()
                ]
                    .filter(Boolean)
                    .join(", ");

                regionName =firstGeoObject.getAdministrativeAreas()[0]; 

                placemarkRef.current.properties.set({
                    iconCaption: newAddress,
                     balloonContent: regionName
                });
            })
    };
    const addCustomMarker = () =>{
        let POINTS = [[55.79424260833246, 49.68814042729016],[55.62832515119459, 49.11135820072768],[55.910118447321, 48.70761064213393]]
        
                // Создание макета содержимого балуна.
        // Макет создается с помощью фабрики макетов с помощью текстового шаблона.
        BalloonContentLayout = ymaps.templateLayoutFactory.createClass(
            '<h1 class="{{ options.colorClass }}">' +
            '{{ properties.header|default:"Title" }}' +
            '</h1>'
        );


        POINTS.forEach(function(pont) {
            var placemark = new ymaps.current.Placemark(pont, {
                name: 'Считаем'
            }, {
                balloonContentLayout: BalloonContentLayout,
                // Запретим замену обычного балуна на балун-панель.
                // Если не указывать эту опцию, на картах маленького размера откроется балун-панель.
                balloonPanelMaxMapArea: 0
            });
            mapRef.current.geoObjects.add(placemark);
        });
    }
    const onMapClick = (e) => {
            let objectManager = new ymaps.current.ObjectManager();
            objectManager.options.set('geoObjectInteractivityModel', 'default#transparent');
                const coords = e.get("coords");
                if (placemarkRef.current) {
                placemarkRef.current.geometry.setCoordinates(coords);
            } else {
                placemarkRef.current = createPlacemark(coords);            
                mapRef.current.geoObjects.add(placemarkRef.current);
                placemarkRef.current.events.add("dragend", function () {
                    getAddress(placemarkRef.current.geometry.getCoordinates());
                });                
            }
            getAddress(coords);
    };

    

    return (    
        <YMaps query={{ 
                        apikey: "106e4ebf-abbc-41b9-9230-adfbc64f15d9" }}>
            <Map defaultState={{
                    center: [55.751574, 37.573856],
                    zoom: 9
                }} 
                modules={["Polygon","GeoObject","geoQuery","control.ZoomControl", "control.FullscreenControl","Placemark", "geocode", 
                "geoObject.addon.balloon","borders", "ObjectManager",'geoObject.addon.balloon','clusterer.addon.balloon',
                'templateLayoutFactory']}
                style={{
                    flex: 2,
                    height: "calc(100vh - 57px)"
                }}
                onClick={onMapClick}    
                instanceRef={mapRef}
                onLoad={(ymapsInstance) => (ymaps.current = ymapsInstance)}
                state={mapState}
            >
                <Button  onClick={addCustomMarker} data={{ content: 'Button' }} options={{ float: 'right' }} />
            </Map>
        </YMaps>
    )
}

export default YMap;

Ответы

Ответов пока нет.