简体   繁体   中英

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

My app needs to access the user's coordinates, but I can't find a way to do this. I'm using Expo, but I'd like to avoid using any Expo libraries as I plan to eject it later and don't want to run into issues when I do so.

I've tried installing react-native-geolocation-service, but I get the following error:

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

Is there any way I can get the device's coordinates without using an Expo library?

For expo, they have their own package for getting the location

Link: 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>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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