如何解决如何在从 React Native 上的 JSON 文件获取数据的地图上显示标记
我正在从这里获取一些数据:https://jsonplaceholder.typicode.com/users 其结构如下:
[
{
"id": 1,"name": "Leanne Graham","username": "Bret","email": "Sincere@april.biz","address": {
"geo": {
"lat": "-37.3159","lng": "81.1496"
}
},},...
]
这是我的代码,我可以在其中获取这些数据并将它们显示在平面列表中
export default class Source extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,dataSource: []
};
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then((responseJson) => {
this.setState({
loading: false,dataSource: responseJson
})
})
.catch(error => console.log(error)) //to catch the errors if any
}
renderItem = (data) =>
<TouchableOpacity >
<Text style={styles.lightText}>{data.item.name}</Text>
<Text style={styles.lightText}>{data.item.address.geo.lng}</Text>
<Text style={styles.lightText}>{data.item.address.geo.lat}</Text></TouchableOpacity>
render() {
return (
<View>
<FlatList
data={this.state.dataSource}
ItemSeparatorComponent={this.FlatListItemSeparator}
renderItem={item => this.renderItem(item)}
keyExtractor={item => item.id.toString()}
/>
</View>
)
}
}
如何使用这些纬度和经度数据在 MapView 中显示它们?此代码将显示 2 个标记,我需要根据该 json 文件显示标记
<MapView style={styles.map}>
<MapView.Marker
coordinate={{
latitude: 45.441831,longitude: 9.190771
}}
/>
<MapView.Marker
coordinate={{
latitude: 46.2222,longitude: 11.1231
}}
/>
</MapView>
解决方法
编辑renderItem函数:
renderItem = (data) => {
return(
<TouchableOpacity style={{flex:1}}>
<Text style={styles.lightText}>{data.item.name}</Text>
<MapView
style={{ height:300 }}
initialRegion={{
latitude: Number(data.item.address.geo.lat),longitude: Number(data.item.address.geo.lng),latitudeDelta: 0.0922,longitudeDelta: 0.0421,}}
>
<MapView.Marker
coordinate={{
latitude: Number(data.item.address.geo.lat),}}
/>
</MapView>
</TouchableOpacity>
)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。