为什么 navigator.geolocation.getcurrentposition 不适用于 React Native 和 Expo

Oth*_*ani 2 android geolocation reactjs react-native expo

我正在尝试从设备获取一些位置信息,我在 Android 移动设备上使用 React-native、Expo 和 ExpoGo,我没有使用模拟器,该应用程序正在 Android 上与 ExpoGo 配合使用,但地理定位不起作用,它会发送每次都会出现此错误消息: window.navigator.geolocation.getCurrentPosition is not available. Import and execute installWebGeolocationPolyfill() from expo-location to add it, or use the expo-location APIs instead.

请帮我找到这个问题的解决方案。

这是使用的应用程序代码:

import { Text, View} from "react-native";
import styles from "./styles";

const API_KEY = "";
const URL = `https://maps.google.com/maps/api/geocode/json?key=${API_KEY}&latlng=`;

export default function WhereAmI() {
  const [address, setAddress] = useState("loading...");
  const [longitude, setLongitude] = useState();
  const [latitude, setLatitude] = useState();

  useEffect(() => {
    function setPosition({ coords: { latitude, longitude } }) {
      setLongitude(longitude);
      setLatitude(latitude);
      fetch(`${URL}${latitude},${longitude}`)
        .then(
          (resp) => resp.json(),
          (e) => console.error(e)
        )
        .then(({ results }) => {
          setAddress(results[0].formatted_address);
        });
    }

    navigator.geolocation.getCurrentPosition(setPosition);

    let watcher = navigator.geolocation.watchPosition(
      setPosition,
      (err) => console.error(err),
      { enableHighAccuracy: true }
    );

    return () => {
      navigator.geolocation.clearWatch(watcher);
    };
  });

  return (
    <View style={styles.container}>
      <Text style={styles.label}>Address: {address}</Text>
      <Text style={styles.label}>Latitude: {latitude}</Text>
      <Text style={styles.label}>Longitude: {longitude}</Text>
    </View>
  );
}
Run Code Online (Sandbox Code Playgroud)

Oth*_*ani 11

我解决了这个问题,这对我有用。

  1. iOS 和 Android 上的地理定位:
  • 我通过运行安装了 expo-location 包expo install expo-location
  • 我在 App.js 中将世博地点导入为 Location: import * as Location from 'expo-location'
  • 在使用 #navigator.geolocation.getCurrentPosition 之前,我使用了 #installWebGeolocationPolyfill 函数,该函数对 #navigator.geolocation 进行了与核心 React Native 和 Web API 地理定位方法的互操作,如下所示:
       # ... some code

      Location.installWebGeolocationPolyfill()
      navigator.geolocation.getCurrentPosition(setPosition);

      # ... some code

Run Code Online (Sandbox Code Playgroud)

2.错误“formatted_address”未定义:因为没有API_KEY,所以您应该从Google获取API密钥,相反,我只是将其手动添加到#setPosition函数中,如下所示:

 #...some code

.then(
          ({ results }) => {
            results[0]={formatted_address:"here"}
            setAddress(results[0].formatted_address)
          },

 #...some code

Run Code Online (Sandbox Code Playgroud)