index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. import { useAmap, usePlugins } from "@amap/amap-react";
  2. import { memo, useEffect, useRef } from "react";
  3. export const DageMapGeocoder = memo(({ city, position, onError, onChange }) => {
  4. const map = useAmap();
  5. const AMap = usePlugins(["AMap.Geocoder"]);
  6. const geocoder = useRef();
  7. useEffect(() => {
  8. if (!map || !AMap)
  9. return;
  10. // @ts-ignore
  11. geocoder.current = new AMap.Geocoder({
  12. city,
  13. });
  14. map.add(geocoder.current);
  15. return () => {
  16. map.remove(geocoder.current);
  17. };
  18. }, [map, AMap, city]);
  19. useEffect(() => {
  20. geocoder.current &&
  21. geocoder.current.getAddress(position, (status, result) => {
  22. if (status === "complete" && result.info === "OK") {
  23. onChange === null || onChange === void 0 ? void 0 : onChange(result);
  24. }
  25. else {
  26. onError === null || onError === void 0 ? void 0 : onError();
  27. }
  28. });
  29. }, [position, onChange]);
  30. return null;
  31. }, (prevProps, nextProps) => prevProps.position[0] === nextProps.position[0] &&
  32. prevProps.position[1] === nextProps.position[1]);