useAmap.ts 974 Bytes
Newer Older
silver47gin's avatar
silver47gin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
import { AMapSdk } from "react-native-amap3d";
import { PermissionsAndroid } from "react-native";
import { useCallback, useEffect } from "react";
import { init, Geolocation, Coordinates } from "react-native-amap-geolocation";

const androidKey = "20071bdcf9a2031ccee484febd627d2e";

export const useAmap = () => {
  useEffect(() => {
    AMapSdk.setApiKey(androidKey);
  }, []);
};

export const useAmapGeoLocation = () => {
  const initSDK = useCallback(async () => {
    await PermissionsAndroid.requestMultiple([
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
    ]);
    await init({
      ios: "",
      android: androidKey,
    });
  }, []);

  useEffect(() => {
    initSDK();
  }, [initSDK]);

  return useCallback(
    () =>
      new Promise<Coordinates>((resolve) => {
        Geolocation.getCurrentPosition(({ coords }) => {
          resolve(coords);
        });
      }),
    []
  );
};