Работаю с Yandex Maps API (React, YMap). Хочу получить текущие границы окна пользователя (видимую область карты).
Пробовал использовать mapInstance.getBounds(), но иногда этот метод недоступен (например, в некоторых версиях ymaps3).
Сейчас мой хук выглядит так:
import { useEffect, useRef } from "react";
import debounce from "lodash/debounce";
import { coord1Changed, coord2Changed } from "@entities/jobs/store";
export const useMapBounds = (mapInstance: any) => {
const prevBounds = useRef<string | null>(null);
useEffect(() => {
if (!mapInstance) return;
const getVisibleBounds = () => {
try {
if (typeof mapInstance.getBounds === "function") {
const bounds = mapInstance.getBounds();
if (bounds) {
return {
minLat: bounds[0][0],
maxLat: bounds[1][0],
minLon: bounds[0][1],
maxLon: bounds[1][1],
};
}
}
if (mapInstance.center && mapInstance.zoom) {
// пробую вычислять вручную
const center = mapInstance.center;
const zoom = mapInstance.zoom;
const size = mapInstance.size || { x: 943, y: 954 };
const zoomFactor = Math.pow(2, zoom);
const latDelta = size.y / 256 / zoomFactor;
const lonDelta = size.x / 256 / zoomFactor;
return {
minLat: center[0] - latDelta,
maxLat: center[0] + latDelta,
minLon: center[1] - lonDelta,
maxLon: center[1] + lonDelta,
};
}
return null;
} catch (error) {
console.error("Error getting visible bounds:", error);
return null;
}
};
const handleBoundsChange = debounce(() => {
const bounds = getVisibleBounds();
if (!bounds) return;
console.log(" bounds updated:", bounds);
}, 500);
if (mapInstance.events?.add) {
mapInstance.events.add("update", handleBoundsChange);
} else {
setInterval(handleBoundsChange, 1000);
}
setTimeout(handleBoundsChange, 1000);
}, [mapInstance]);
};
Как правильно получить границы видимой области карты (bounds) в Yandex Maps API (особенно для ymaps3)?
Есть ли встроенный метод вроде getBounds(), или bounds нужно вычислять вручную через center, zoom и size?