javascript - 在 React Native 中获取 API 之前如何保存当前位置的经纬度坐标?

标签 javascript android reactjs google-maps react-native

大家好,

我在 Geolocation 上遇到了一些问题,我正在访问我的当前位置以使用我的 Link API 上的经纬度,但我遇到了一些无法访问 API 的问题,结果是最初找不到 JSON 数据,当我测试它们时,我将它们保存到单独的变量中但不能正常工作,现在如何在获取 API 之前保存它们?

Error

我的代码在这里:

    import React, { Component } from "react";
    import {
      StyleSheet,
      Text,
      View,
      TextInput,
      ScrollView,
      Image,
      ActivityIndicator
    } from "react-native";
    import Icon from "react-native-vector-icons/dist/FontAwesome";


    export default class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          isLoading: true,
          dataSource: [],
          latitude: null,
          longitude: null,
          error: null
        };
      }
      async componentDidMount() {
        this.watchId = navigator.geolocation.watchPosition(
          position => {
            this.setState({
              latitude: position.coords.latitude,
              longitude: position.coords.longitude,
              error: null
            });
          },
          error => this.setState({ error: error.message }),
          {
            enableHighAccuracy: true,
            timeout: 20000,
            maximumAge: 1000,
            distanceFilter: 5
          }
        );
    var myLat = `${this.state.latitude}`;
        var myLon = `${this.state.longitude}`;
     let API_WEATHER = `http://api.openweathermap.org/data/2.5/weather?lat=${myLat}&lon=${myLon}&units=metric&appid=${API_KEY}`;

fetch(API_WEATHER)
      .then(response => response.json())
      .then(responseJson => {
        console.log(responseJson);
        console.log(responseJson.weather);
        this.setState({
          isLoading: false,
          dataSource: responseJson
        });
      })
      .catch(error => {
        console.log(error);
      });
  }

render() {
    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, padding: 20 }}>
          <ActivityIndicator size="large" />
        </View>
      );
    }
 var icon =
      this.state.dataSource.main.temp <= 20
        ? require("./assets/cloudySun.png")
        : require("./assets/sunny.png");
    return (
      <ScrollView style={styles.container}>
        <View style={styles.head}>
          <Text style={styles.titleApp}>Weather App</Text>
          <View
            style={{
              flexGrow: 1,
              alignItems: "center",
              justifyContent: "center"
            }}
          >
            <Text>Latitude: {this.state.latitude}</Text>
            <Text>Longitude: {this.state.longitude}</Text>
            {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
          </View>
        </View>
        <View style={styles.defaultWeather}>
          <View style={styles.infoDegree}>
            <Text style={{ fontSize: 80, color: "#42434B", paddingBottom: 0 }}>
              {this.state.dataSource.main.temp}°
            </Text>
            <Text style={{ fontSize: 16, padding: 7 }}>
              {this.state.dataSource.name},{this.state.dataSource.sys.country}
            </Text>
            <Text style={{ color: "#42434B", fontSize: 20, padding: 2 }}>
              {this.state.dataSource.weather[0].description}
            </Text>
          </View>
 var icon =
      this.state.dataSource.main.temp <= 20
        ? require("./assets/cloudySun.png")
        : require("./assets/sunny.png");
    return (
      <ScrollView style={styles.container}>
        <View style={styles.head}>
          <Text style={styles.titleApp}>Weather App</Text>
          <View
            style={{
              flexGrow: 1,
              alignItems: "center",
              justifyContent: "center"
            }}
          >
            <Text>Latitude: {this.state.latitude}</Text>
            <Text>Longitude: {this.state.longitude}</Text>
            {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
          </View>
        </View>
        <View style={styles.defaultWeather}>
          <View style={styles.infoDegree}>
            <Text style={{ fontSize: 80, color: "#42434B", paddingBottom: 0 }}>
              {this.state.dataSource.main.temp}°
            </Text>
            <Text style={{ fontSize: 16, padding: 7 }}>
              {this.state.dataSource.name},{this.state.dataSource.sys.country}
            </Text>
            <Text style={{ color: "#42434B", fontSize: 20, padding: 2 }}>
              {this.state.dataSource.weather[0].description}
            </Text>
          </View>
         </View>
</ScrollView>



const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 5,
    backgroundColor: "#F2F4FA"
  },
  head: {
    alignItems: "center"
  },
  titleApp: {
    fontSize: 20,
    fontWeight: "400",
    color: "#000"
  },
  defaultWeather: {
    flexDirection: "row",
    justifyContent: "space-between"
  },
  infoDegree: {
    padding: 15,
    marginBottom: 20
  },
  searchSection: {
    marginBottom: 50,
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#fff",
    shadowColor: "#eee",
    shadowOffset: { width: 10, height: 3 },
    shadowOpacity: 0.8,
    shadowRadius: 10,
    elevation: 5
  },
  searchIcon: {
    padding: 10
  },
  input: {
    flex: 1,
    paddingTop: 10,
    paddingRight: 10,
    paddingBottom: 10,
    paddingLeft: 0,
    backgroundColor: "#fff",
    color: "#424242"
  },
  statusWeather: {
    width: 210,
    padding: 20,
    margin: 10,
    backgroundColor: "#e8ebf7"
  },
  ImgWeek: {
    marginTop: 10,
    marginBottom: 23
  },
  TextStatus: {
    color: "#607498",
    fontSize: 17,
    padding: 10
  }
});

最佳答案

尝试以下操作,将回调传递给 setState,在那里您将获得新的经纬度:

  componentDidMount() {
            this.watchId = navigator.geolocation.watchPosition(
              position => {
                this.setState({
                  latitude: position.coords.latitude,
                  longitude: position.coords.longitude,
                  error: null
                },()=>{
        var myLat = `${this.state.latitude}`;
            var myLon = `${this.state.longitude}`;
         let API_WEATHER = `http://api.openweathermap.org/data/2.5/weather?lat=${myLat}&lon=${myLon}&units=metric&appid=${API_KEY}`;

    fetch(API_WEATHER)
          .then(response => response.json())
          .then(responseJson => {
            console.log(responseJson);
            console.log(responseJson.weather);
            this.setState({
              isLoading: false,
              dataSource: responseJson
            });
          })
          .catch(error => {
            console.log(error);
          });

});
              },
              error => this.setState({ error: error.message }),
              {
                enableHighAccuracy: true,
                timeout: 20000,
                maximumAge: 1000,
                distanceFilter: 5
              }
            );

      }

关于javascript - 在 React Native 中获取 API 之前如何保存当前位置的经纬度坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53804690/

相关文章:

android - DOM - 从节点解析文本

android - 丢失 .idea 文件夹后如何在 Android Studio 中重新创建项目?

javascript - 如何使用钩子(Hook)在 React 组件之间传递状态?

javascript - 如何居中对齐 Material-ui TextField 文本并设置最小数值?

reactjs - 如何在react js中渲染这个JSON对象

javascript - 无法在 Material UI TextField 中键入文本

javascript - NoUISlider 不工作

java - 无法选中底部导航 View 项目

javascript - 更改没有名称的属性的处理程序

javascript - Chrome "Copy image"选项在右键单击上下文菜单中呈灰色