繁体   English   中英

如何在 React Native 中获取设备的地理位置?

[英]How can I get a device's geolocation in React Native?

我的应用程序需要访问用户的坐标,但我找不到这样做的方法。 我正在使用 Expo,但我想避免使用任何 Expo 库,因为我计划稍后将其弹出并且不想在这样做时遇到问题。

我尝试安装 react-native-geolocation-service,但出现以下错误:

'new NativeEventEmitter()' requires a non-null argument.

有什么方法可以在不使用 Expo 库的情况下获取设备的坐标?

对于 expo,他们有自己的 package 用于获取位置

链接: https://docs.expo.dev/versions/latest/sdk/location/

expo install expo-location
import React, { useState, useEffect } from 'react';
import { Platform, Text, View, StyleSheet } from 'react-native';
import * as Location from 'expo-location';

export default function App() {
  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);

  useEffect(() => {
    (async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
        return;
      }

      let location = await Location.getCurrentPositionAsync({});
      setLocation(location);
    })();
  }, []);

  let text = 'Waiting..';
  if (errorMsg) {
    text = errorMsg;
  } else if (location) {
    text = JSON.stringify(location);
  }

  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>{text}</Text>
    </View>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM