react-native - 如何在 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;
请协助我在这里有点困惑。我只需要它来动态获取它并在地图中显示方向。
解决方案
首先,你需要一个新的钩子来让你的 API 运行。通过使用 useEffect 来实现这一点。
具有空数组依赖项的 UseEffect 只会在加载时运行您的 API 一次。使用 API 的结果,使用 useState 中的 set 方法来更新 Coordinates 变量。然后,您可能会看到坐标动态更新。
const ShowMap =() =>{
const [Coordinates, setCoordinates] = useState();
useEffect(() => {
(async () => {
const result = GetLongitudeFromAddress(param);
setCoordinates(result);
})();
}, []);
return (<Map/>)
}
推荐阅读
- testing - 使用 Jenkins 进行 Ant SOA 测试
- vue.js - 通过 WP REST API 的 Vue.js 导航子菜单
- angular - 提供者无法解析构造函数参数中的其他提供者
- python - Ubuntu 上的 Apache2 给出 Py_Initialize ImportError: No module named encodings
- qliksense - qliksense 没有从 hive 获得更长的字符串
- chisel - 在凿子中将参数传递给验证器后端
- c# - Json.NET C#:根据集合字段是否已用某个属性装饰来序列化集合
- swift - 多个页面浏览控制器滚动
- office365 - 如何在不授予“以任何用户身份发送邮件”权限的情况下在服务中的 office 365 REST API V2.0 中发送邮件?
- r - R嵌套模型:创建模型公式列