Пытаюсь сделать кластеры но при создании одной карты появляются две одна со всеми функциями а другая без них, так же когда кластеризация происходит все метки дублируются скорее всего из за этих двух карт или чего то подобного При наведении
export const AppMap = ({ marks, initialState = null, scannedCoordinate = null, officeMarks = null }: {marks: IAppMapData[], initialState: IAppMapState | null, scannedCoordinate: [string, string] | null | undefined, officeMarks: IAppMapData[] | null }) => {
const [mapState, setMapState] = useState<MapState | null>(null);
const [isAnchor, setIsAnchor] = useState<boolean>(false);
const [map, setMap] = useState<YMapsApi | null>(null);
const [marksWithIcons, setMarksWithIcons] = useState<IAppMapData[]>([]);
const [officeMarksWithIcons, setOfficeMarksWithIcons] = useState<IAppMapData[]>([]);
const [cluster, setCluster] = useState({
layout: null
});
const mapRef = useRef(null);
const router = useRouter();
const {width} = useWindowDimensions();
const counts: any = useSelector((state ) => state.MenuState.menu[0].items);
const scrollToMap = () => {
scroller.scrollTo('map', {
duration: 800,
delay: 0,
smooth: 'easeInOutQuart'
});
};
// Создание иконки метки
const createPlaceMarkLayout = (icon: string) => {
if (map) {
return map
.templateLayoutFactory
.createClass(
`<div style="display: flex; align-items: center; width: 24px; height: 24px;">
<img src="${icon}" alt="" style="object-fit: contain;">
</div>`
);
}
};
// Создание иконки метки с хинтом
const createPlaceMarkWithTextLayout = (icon: string, text: string, index: number) => {
if (map) {
return map
.templateLayoutFactory
.createClass(
`<div style="display: flex; align-items: center; width: 24px; height: 24px;">
<div class='${styles['appMap__mark-info']}'>
<div class="${styles['appMap__mark-section']}">
<div class="${styles['appMap__mark-img']}">
${icon ? `<img src="${icon}" alt="${text}">` : ''}
</div>
<section class="${styles['appMap__mark-content']}">
<span>${text}</span>
<section>
<span class={styles['project-item__count']}>
${counts[index].landsCount > 0 ? `${counts[index].landsCount} ${declOfNum(counts[index].landsCount, ['участок ', 'участка ', 'участков '])}`: 'Проект реализован'}
</span>
<span>
${counts[index].landsPriceFrom ? ` от ${numberSeparator(counts[index].landsPriceFrom)} ₽` : ''}
</span>
</section>
</section>
</div>
</div>
<img src="${icon}" alt="" style="object-fit: contain;">
</div>`
);
}
};
// Создание иконки метки
const createClusterLayout = () => {
if (map) {
const layout = map
.templateLayoutFactory
.createClass(
`<div style="display: flex; align-items: center; width: 24px; height: 24px;">
<div onclick="{console.log({ properties.geoObjects.length})}" class='${styles['appMap__cluster-info']}'>
<div class="${styles['appMap__cluster-number']}">{{ properties.geoObjects.length}}</div>
</div>
</div>`
);
setCluster({
layout
});
}
};
const instanceRef = (mapObject: any) => {
if (mapObject) {
mapObject.behaviors.disable('scrollZoom');
if (isMobile) {
mapObject.behaviors.disable('drag');
} else {
mapObject.behaviors.disable('multiTouch');
}
}
};
useEffect(() => {
if (map) {
const newMarks: IAppMapData[] = [];
const newOfficeMarks: IAppMapData[] = [];
marks.map((mark: IAppMapData, index: number) => {
const iconLayout = createPlaceMarkLayout(mark.logo);
const iconWithTextLayout = createPlaceMarkWithTextLayout(mark.logo, mark.text, index);
newMarks.push({
...mark,
iconLayout,
iconWithTextLayout
});
});
setMarksWithIcons(newMarks);
setOfficeMarksWithIcons(newOfficeMarks);
createClusterLayout();
}
}, [map]);
useEffect(() => {
const onKeypress = (event: KeyboardEvent) => {
if (event.ctrlKey) {
console.log('ctrlKey');
}
};
document.addEventListener('keydown', onKeypress);
return () => {
document.removeEventListener('keydown', onKeypress);
};
}, []);
useEffect(() => {
const multiTouch: string = width && width <= 768 ? 'multiTouch' : 'drag';
const behaviors = ["disable('scrollZoom')", 'dblClickZoom', multiTouch];
if (initialState) {
setMapState({
center: [Number.parseFloat(initialState.center.lat), Number.parseFloat(initialState.center.lng)],
zoom: initialState.zoom,
behaviors,
controls: [],
});
} else if (marks.length > 0) {
const firstMark: IAppMapData = marks[0];
setMapState({
center: [Number.parseFloat(firstMark.center.lat), Number.parseFloat(firstMark.center.lng)],
zoom: firstMark.zoom,
behaviors,
controls: [],
});
}
}, [initialState, marks]);
useEffect(() => {
if (scannedCoordinate) {
setMapState({
mapState,
center: [Number.parseFloat(scannedCoordinate[0]), Number.parseFloat(scannedCoordinate[1])],
zoom: 15
});
}
}, [scannedCoordinate]);
useEffect(() => {
if (isAnchor) {
setTimeout(function goToMap() {
if (!mapRef) {
setTimeout(goToMap, 100);
} else {
scrollToMap();
}
}, 100);
}
}, [isAnchor]);
return mapState && (
<div id="map" className={styles['appMap']}>
<YMaps query={{
load: "package.full"
}}>
<Map
instanceRef={ref => instanceRef(ref)}
onLoad={(ymaps: YMapsApi) => setMap(ymaps)}
width="100%"
height="100%"
position='absolute'
state={mapState}
>
<Clusterer
options={{
preset: "islands#invertedVioletClusterIcons",
groupByCoordinates: false
}}
>
{marksWithIcons.map((mark: IAppMapData, index: number) => {
return (
<Placemark
key={index}
geometry={[Number.parseFloat(mark.point.lat), Number.parseFloat(mark.point.lng)]}
onMouseEnter={(e: any) => {
e.get('target').options.set('iconContentLayout', mark.iconWithTextLayout);
}}
onMouseLeave={(e: any) => {
e.get('target').options.set('iconContentLayout', mark.iconLayout);
}}
onClick={(e: any) => router.push(`/projects/${mark.path}`)}
options={{
iconLayout: 'default#imageWithContent',
iconImageHref: '/images/map-icon.png',
iconImageSize: [64, 64],
iconImageOffset: [-32, -32],
iconContentOffset: [20, 20],
iconContentLayout: mark.iconLayout
}}
/>
);})}
{officeMarksWithIcons.length > 0 && (
<>
{officeMarksWithIcons.map((mark: IAppMapData, index: number) => {
return (
<Placemark
key={index}
geometry={[Number.parseFloat(mark.point.lat), Number.parseFloat(mark.point.lng)]}
onMouseEnter={(e: any) => {
e.get('target').options.set('iconContentLayout', mark.iconWithTextLayout);
}}
onMouseLeave={(e: any) => {
e.get('target').options.set('iconContentLayout', mark.iconLayout);
}}
options={{
iconLayout: 'default#imageWithContent',
iconImageHref: '/images/map-icon.png',
iconImageSize: [64, 64],
iconImageOffset: [-32, -32],
iconContentOffset: [20, 20],
iconContentLayout: mark.iconLayout
}}
properties={{
balloonContent: `
<img src=${mark.logo} alt=${mark.text}>
<p>${mark.text}</p>
<a href="/projects/${mark.path}">Больше информации...</Link>
`,
hintContent: `
<img src=${mark.logo} alt=${mark.text}>
<p>${mark.text}</p>
<a href="/projects/${mark.path}">Больше информации...</Link>
`,
}}
/>
);
})}
</>
)}
</Clusterer>
<ZoomControl />
</Map>
</YMaps>
</div>
);
};