首页 > 解决方案 > 如何在 usestate 中使用从 REST api 获得的经度/纬度

问题描述

我是使用 Getstate 和 UseState 的新手通常,当我对经度和纬度进行硬编码时,它可以正常工作,现在我想直接从输入的地址获取经度和纬度。我已将值设置为 setstate,但我不熟悉使用 setstate,使用 state。我写了一个方法来获取地址。因此,在获得地址后应该解决获得经度/纬度

这得到了经度和纬度

GetLongitudeFromAddress = (txtaddress) =>{

    let address = txtaddress;
    let lng = this.state.Alongitude;
    let lat = this.state.Alatitude;

    var logLatApi = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false&key=AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE';

    var header = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    };

    fetch(
        logLatApi,{
            method : 'GET',
            headers : header
        }
    ).then((response) => response.json())
    .then((responseJson)=>{
        if(responseJson.status ==='OK')
        {
            this.setState({longitude: responseJson.results[0].geometry.location.lng});
            this.setState({latitude: responseJson.results[0].geometry.location.lat});
        }
    })
}

现在我想在我的 setstate / usestate 中使用它

 const [coordinates] = useState([
        {
          latitude: 6.450430,
          longitude: 3.390460,
        },
        {
          latitude: 6.430980,
          longitude: 3.435880,
        },
      ]);

我怎样才能做到这一点?我的完整代码如下所示:

import React , {useState} from 'react';
import {StyleSheet, View, Dimensions, TextInput} from 'react-native';
import MapView , { Marker , Polyline } from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

this.state = {
    Address : '',
    Alongitude : '',
    Alatitude: '',
  };


GetLongitudeFromAddress = (txtaddress) =>{

    let address = txtaddress;
    let lng = this.state.Alongitude;
    let lat = this.state.Alatitude;

    var logLatApi = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false&key=AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE';

    var header = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    };

    fetch(
        logLatApi,{
            method : 'GET',
            headers : header
        }
    ).then((response) => response.json())
    .then((responseJson)=>{
        if(responseJson.status ==='OK')
        {
            this.setState({longitude: responseJson.results[0].geometry.location.lng});
            this.setState({latitude: responseJson.results[0].geometry.location.lat});
        }
    })
}

const ShowMap =() =>{

    const [coordinates] = useState([
        {
          latitude: 6.450430,
          longitude: 3.390460,
        },
        {
          latitude: 6.430980,
          longitude: 3.435880,
        },
      ]);

    return(
        
        <View style={styles.container}>
        <MapView
          style={styles.maps}
          initialRegion={{
            latitude: coordinates[0].latitude,
            longitude: coordinates[0].longitude,
            latitudeDelta: 0.0622,
            longitudeDelta: 0.0121,
          }}>
          <MapViewDirections
            origin={coordinates[0]}
            destination={coordinates[1]}
            apikey="AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE"
            strokeWidth={4}
            strokeColor="#FD0631"
          />
          <Marker coordinate={coordinates[0]} />
          <Marker coordinate={coordinates[1]} />
        </MapView>
        <View style={styles.inputView}>
                <TextInput 
                style={styles.input}
                placeholder="Origin"
                onChange={this.GetLongitudeFromAddress()}
                />
                <TextInput 
                style={styles.input}
                placeholder="Destination"
                onChange={this.GetLongitudeFromAddress()}
                />
            </View>
      </View>
    );
}


const styles = StyleSheet.create({
    container: {
      flex: 1,
    },
    maps: {
      width: Dimensions.get('screen').width,
      height: Dimensions.get('screen').height,
    },
    inputView:{
        backgroundColor: 'rgba(0,0,0,0)',
        position: 'absolute', 
        top: 0,
        left: 5,
        right: 5
    },
    input: {
        height: 50,
        padding: 10,
        marginTop: 20,
        marginLeft: 10,
        marginRight: 10,
        fontSize: 18,
        borderWidth: 1,
        borderRadius: 35,
        borderColor: '#EEEEEE',
        backgroundColor: 'white',
    }
  });



export default ShowMap;

请协助我在这里有点困惑。我只需要它来动态获取它并在地图中显示方向。

标签: react-nativelatitude-longitudeuse-state

解决方案


首先,你需要一个新的钩子来让你的 API 运行。通过使用 useEffect 来实现这一点。

具有空数组依赖项的 UseEffect 只会在加载时运行您的 API 一次。使用 API 的结果,使用 useState 中的 set 方法来更新 Coordinates 变量。然后,您可能会看到坐标动态更新。

const ShowMap =() =>{
    const [Coordinates, setCoordinates] = useState();

    useEffect(() => {
      (async () => {
          const result = GetLongitudeFromAddress(param);
          setCoordinates(result);
       })();
    }, []);

    return (<Map/>)
}

推荐阅读