【问题标题】:City location in expo location react-native世博会地点中的城市位置反应原生
【发布时间】:2021-03-01 06:06:20
【问题描述】:

我正在尝试使用 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],但由于某种原因,我唯一得到的是它:[未处理的承诺拒绝:错误:“城市”是只读的] 为什么是只读的?我没听懂...有人可以帮我吗?

【问题讨论】:

    标签: arrays string react-native city


    【解决方案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

    【讨论】:

    • 真的好用!非常感谢您的帮助。
    • 现在我正在尝试使用用户位置获得相同的结果,但我无法获得它。我该怎么办?我正在尝试使用 reverseGeocodeAsync({}) 从 getCurrentPositionAsync({}) 获取纬度和经度,我该怎么做?
    • 用户位置是指从设备获取的当前位置?
    • 如果是那么我已经更新了代码:snack.expo.io/@xeteke8423/crabby-pretzel
    • 我试着看看我还能做些什么,最后,我弄清楚了它需要什么并且我能够得到它。再次非常感谢您有兴趣帮助我
    猜你喜欢
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2021-02-02
    • 2020-05-17
    相关资源
    最近更新 更多