Stack Overflow на русском Asked on November 10, 2021
Как в react-yandex-maps получить координаты всех полигонов карты или только что добавленного?
<YMaps>
<Map
height="480px"
width="auto"
defaultState={{ center: [defaultLat, defaultLon], zoom }}
modules={['geoObject.addon.balloon', 'geoObject.addon.hint', 'geoObject.addon.editor']}
>
<Polygon
instanceRef={instanceRef}
geometry={[]}
options={{
draggable: true,
editorDrawingCursor: 'crosshair',
strokeColor: colors.primary,
strokeOpacity: 0.5,
strokeWidth: 3,
}}
/>
</Map>
</YMaps>
Вопрос решен. Refs (instanceRef) в помощь
const Map: React.FC<IMapProps> = ({
placemarks,
polygons: defaultPolygons,
defaultLat = 0,
defaultLon = 0,
zoom = DEFAULT_MAP_ZOOM,
}) => {
const { t } = useTranslation();
const [isEditMode, setIsEditMode] = useState(false);
const [polygons, setPolygons] = useState(defaultPolygons || []);
const [coordinates, setCoordinates] = useState([]);
const toggleIsEditMode = (): void => {
setIsEditMode((prevIsEditable) => !prevIsEditable);
};
const instanceRef = useCallback((ref: any) => {
if (ref) {
ref.editor.startDrawing();
ref.geometry.events.add('change', (e: any) => setCoordinates(e.get('newCoordinates')));
}
}, []);
const resetCoordinates = useCallback(() => {
setCoordinates([]);
setIsEditMode(false);
}, []);
const saveCoordinates = useCallback(() => {
setPolygons([...polygons, ...coordinates]);
resetCoordinates();
// @todo: to add save request
}, [coordinates, polygons, resetCoordinates]);
return (
<YMaps>
{polygons.length && (
<Row className={styles.controls}>
{isEditMode ? (
<Space>
<Button onClick={saveCoordinates}>{t('buttons.save')}</Button>
<Button onClick={resetCoordinates}>{t('buttons.reset')}</Button>
</Space>
) : (
<Button onClick={toggleIsEditMode}>{t('buttons.addPolygon')}</Button>
)}
</Row>
)}
<YandexMap
height="480px"
width="auto"
defaultState={{ center: [defaultLat, defaultLon], zoom }}
modules={['geoObject.addon.balloon', 'geoObject.addon.hint', 'geoObject.addon.editor']}
>
<MapPlacemarks placemarks={placemarks} />
<MapPolygon polygons={polygons} />
{isEditMode && (
<Polygon
instanceRef={instanceRef}
geometry={coordinates}
options={{
draggable: true,
editorDrawingCursor: 'crosshair',
strokeColor: colors.primary,
strokeOpacity: 0.5,
strokeWidth: 3,
}}
/>
)}
</YandexMap>
</YMaps>
);
};
Answered by mashuxa on November 10, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP