Расположение города в месте проведения выставки react-native

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

1    import React, { useState, useEffect } from 'react';
2    import { Text, View, StyleSheet } from 'react-native';
3    import * as Location from 'expo-location';
4    
5    export default function App() {
6      const [location, setLocation] = useState(null);
7      const [errorMsg, setErrorMsg] = useState(null);
8    
9      useEffect(() => {
10       (async () => {
11          let { status } = await Location.requestPermissionsAsync();
12          if (status !== 'granted') {
13            setErrorMsg('Permission to access location was denied');
14          }
15    
16          let regionName = await Location.reverseGeocodeAsync( { longitude: 37.6172999, latitude: 55.755826 } );
17          setLocation(regionName);
18          console.log(regionName);
19       })();
20      }, []);
21    
22      let text = 'Waiting..';
23      if (errorMsg) {
24        text = errorMsg;
25      } else if (location) {
26        text = JSON.stringify(location);
27      }
28    
29      return (
30        <View style={styles.container}>
31          <Text>{text}</Text>
32        </View>
33      );
34    }
35    
36    const styles = StyleSheet.create({
37      container: {
38        flex: 1,
39        backgroundColor: '#bcbcbc',
40        alignItems: 'center',
41        justifyContent: 'center',
42      },
43      big: {
44        fontSize: 18,
45        color: "white",
46      }
47    });
48

Итак, я попытался получить только местоположение города, изменив строку 26 на text = JSON.stringify([0].city);, но на моем телефоне больше ничего не отображается ...

Терминал показывает мне этот журнал из console.log:

Array [
  Object {
    "city": "Moscow",
    "country": "Russia",
    "district": "Central Administrative Okrug",
    "isoCountryCode": "RU",
    "name": "109012",
    "postalCode": "109012",
    "region": null,
    "street": null,
    "subregion": "Moscow",
    "timezone": null,
  },
]

Если кто-то может помочь мне найти способ узнать местоположение города, я был бы очень рад

Я подумал, что это может мне помочь, если я попытаюсь получить такой город, ПЕРЕМЕН СО СТРОКИ 22 НА СТРОКУ 27 НА ЭТО:

const city = "Waiting..."
if (errorMsg) {
city = errorMsg;
} else if (location) {
city = Object.keys(regionName).reduce((result, key) => {
  return result.concat(regionName[key].city)
}, []);
};

чтобы получить только массив [0], но по какой-то причине я получил только следующее: [Отклонение необработанного обещания: Ошибка: город доступен только для чтения] Почему только для чтения? Я не понял ... Кто-нибудь может мне помочь?


person GNeto    schedule 18.11.2020    source источник


Ответы (1)


Снимок экрана:

Снимок экрана

Вот рабочий пример:

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_KEY';

// 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 [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 regionName = await Location.reverseGeocodeAsync({
        latitude: 19.2514799,
        longitude: 75.7138884,
      });

      setLocation(regionName);
      console.log(regionName, 'nothing');

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


  return (
    <View style={styles.container}>
      <Text style={styles.big}>
        {!location ? 'Waiting' : JSON.stringify(location[0]["city"])}
      </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"
  }
});

Живая демонстрация: Expo Snack

person Ketan Ramteke    schedule 18.11.2020
comment
Это действительно работает! Большое спасибо за Вашу помощь. - person GNeto; 19.11.2020
comment
Теперь я пытаюсь получить тот же результат, используя местоположение пользователя, но не могу его получить. Что я должен делать? Я пытаюсь использовать reverseGeocodeAsync ({}) для получения широты и долготы из getCurrentPositionAsync ({}), как мне это сделать? - person GNeto; 26.11.2020
comment
местоположение пользователя означает текущую позицию, полученную с устройства? - person Ketan Ramteke; 26.11.2020
comment
Если да, то я уже обновил код: snack.expo.io/@xeteke8423/crabby- крендель - person Ketan Ramteke; 26.11.2020
comment
Я попытался понять, что еще я могу сделать, и, наконец, понял, что Это нужно, и смог это получить. Еще раз большое спасибо за ваш интерес в помощи мне - person GNeto; 28.11.2020