48 lines
1.3 KiB
TypeScript
48 lines
1.3 KiB
TypeScript
import React, { useEffect, useState } from "react";
|
||
import { useMap } from "../MapComponent";
|
||
|
||
const Scale: React.FC = () => {
|
||
const map = useMap();
|
||
const [zoomLevel, setZoomLevel] = useState(0);
|
||
const [coordinates, setCoordinates] = useState<[number, number]>([0, 0]);
|
||
|
||
useEffect(() => {
|
||
if (!map) return;
|
||
|
||
const updateZoomLevel = () => {
|
||
const zoom = map.getView().getZoom();
|
||
setZoomLevel(zoom ?? 0); // 如果 zoom 是 undefined,则使用默认值 0
|
||
};
|
||
|
||
const updateCoordinates = (event: any) => {
|
||
const coords = event.coordinate;
|
||
const transformedCoords = coords.map((c: number) =>
|
||
parseFloat(c.toFixed(4))
|
||
);
|
||
setCoordinates(transformedCoords);
|
||
};
|
||
|
||
map.on("moveend", updateZoomLevel);
|
||
map.on("pointermove", updateCoordinates);
|
||
|
||
// Initialize values
|
||
updateZoomLevel();
|
||
|
||
return () => {
|
||
map.un("moveend", updateZoomLevel);
|
||
map.un("pointermove", updateCoordinates);
|
||
};
|
||
}, [map]);
|
||
|
||
return (
|
||
<div className="absolute bottom-0 right-0 flex col-auto px-2 bg-white bg-opacity-70 text-black rounded-tl shadow-md text-sm z-1300">
|
||
<div className="px-1">缩放: {zoomLevel.toFixed(1)}</div>
|
||
<div className="px-1">
|
||
坐标: {coordinates[0]}, {coordinates[1]}
|
||
</div>
|
||
</div>
|
||
);
|
||
};
|
||
|
||
export default Scale;
|