Местоположение выставки не имеет адресного модуля

#reactjs #react-native #expo

#reactjs #react-native #выставка

Вопрос:

введите описание изображения здесь

Я пытаюсь получить текущее местоположение для своего проекта, но это выдает мне эту ошибку, даже если я установил expo-location

Может кто-нибудь помочь мне исправить эту ошибку?

Большое вам спасибо

Комментарии:

1. как вы можете видеть в документации: docs.expo.io/versions/latest/sdk/location , Местоположение не предоставляет поле адреса

Ответ №1:

Удалить <Location.Address>

Конечный результат:

введите описание изображения здесь

Вот полный рабочий пример.

Используйте свой собственный ключ Maps API для использования reverseGeocodeAsync .

 import React, { useEffect, useState } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

let apiKey = 'YOUR_API_KEYS';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
import * as Location from 'expo-location';

export default function App() {
  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  const [address, setAddress] = useState(null);
  const [getLocation, setGetLocation] = useState(false);

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

      Location.setGoogleApiKey(apiKey);

      console.log(status);

      let { coords } = await Location.getCurrentPositionAsync();

      setLocation(coords);

      console.log(coords);

      if (coords) {
        let { longitude, latitude } = coords;

        let regionName = await Location.reverseGeocodeAsync({
          longitude,
          latitude,
        });
        setAddress(regionName[0]);
        console.log(regionName, 'nothing');
      }

      // console.log();
    })();
  }, [getLocation]);

  return (
    <View style={styles.container}>
      <Text style={styles.big}>
        {!location
          ? 'Waiting'
          : `Lat: ${location.latitude} nLong: ${
              location.longitude
            } n${JSON.stringify(address?.["subregion"])}`}
      </Text>
      <TouchableOpacity onPress={() => setGetLocation(!getLocation)}>
        <View
          style={{
            height: 100,
            backgroundColor: 'teal',
            justifyContent: 'center',
            alignItems: 'center',
            borderRadius: 10,
            marginTop: 20,
          }}>
          <Text style={styles.btnText}> GET LOCATION </Text>
        </View>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    alignItems: 'center',
    justifyContent: 'center',
  },
  big: {
    fontSize: 18,
    color: 'black',
    fontWeight: 'bold',
  },
  btnText: {
    fontWeight: 'bold',
    fontSize: 25,
    color: 'white',
  },
});
 

Вы можете поиграть с рабочим кодом здесь: Ссылка на выставку