首页 > 解决方案 > 添加地理位置以创建 React Native App

问题描述

我使用最新的 Expo CLI 使用React Native 文档中的说明创建了我的第一个 React Native 应用程序:

npm install -g expo-cli
npm expo init AwesomeProject

后来我想将地理定位库添加到这个应用程序中,似乎整个自动链接不适合我。我使用了提供的说明:

yarn add @react-native-community/geolocation

而且我还没有完成手动链接,因为我在当前最新版本中使用 React Native(如库的自述文件中所述,高于 0.59)。添加示例代码后:

import Geolocation from '@react-native-community/geolocation';
Geolocation.getCurrentPosition(info => console.log(info));

我已经开始收到应该链接库的错误。手动调用链接命令后,不幸的是它仍然没有工作。

标签: androidreact-nativegeolocationexpo

解决方案


实际上,我跳出了这些库并对此进行了完整的博览会(但我仍然不确定这是否是正确的方法):

import { useState, useEffect } from "react";
import * as Permissions from "expo-permissions";
import * as Location from "expo-location";

export const useLocation = () => {
  const [location, setLocation] = useState();

  useEffect(() => {
    async function setLocationWithPerms() {
      const permissions = await Permissions.askAsync(Permissions.LOCATION);

      if (permissions.status === "granted") {
        const currentLocation = await Location.getCurrentPositionAsync({});
        setLocation(currentLocation);
      }
    }
    setLocationWithPerms();
  }, []);

  return location;
};

推荐阅读