【问题标题】:Displaying MapView markers from JSON API从 JSON API 显示 MapView 标记
【发布时间】:2019-09-05 17:49:19
【问题描述】:

我正在使用 React Native 地图视图 (https://github.com/react-native-community/react-native-maps) 并已成功让我的地图使用手动标记显示。但是,当我尝试显示我获取的 JSON 数据标记时,我得到了持续的语法错误。

import MapView from 'react-native-maps'
import { Marker } from 'react-native-maps';

constructor(props) {
    super(props);
    this.state = {
     myMarkers: []
};
  }
componentDidMount() {
   this.getMarkers();
  }

getMarkers() {
    axios
      .get("MYAPISOURCE")
      .then(response => {
        this.setState({
          myMarkers: response.data.responser
        });
      });
  }

render() {
    return (
<MapView style={styles.map}
   rotateEnabled={false}
          initialRegion={{
              latitude: 37.78825,
              longitude: -122.4324,
              latitudeDelta: 0.04,
              longitudeDelta: 0.05,
          }}
        >

   {this.state.myMarkers.map((post, index)=> {
          <MapView.Marker
            key={post.ID}
            coordinate={{
                    latitude:{post.lat},
                    longitude:{post.lng}}}
          />
                 })}


      </MapView>

);
    }

我的地图视图代码不断出现语法错误:坐标函数中出现意外标记,应为“,”。我尝试了很多不同的选项,但是当我有我的标记代码时,我无法让标记和地图工作。

但是,如果我在 MapView 之外运行以下代码,它会成功显示我的数据,因此我的 API 调用和 myMarkers 状态正在运行并具有正确的数据:

    {this.state.myMarkers.map((post, index)=> {

        return (
         <View key={index}>
          <Text>
            {post.lat},
            {post.lat}
          </Text>
         </View>
        )
      })}

这将显示以下内容: 37.78825, -122.4324 33.78825, -121.4324 31.78825, -124.4324

【问题讨论】:

    标签: json react-native mkmapview


    【解决方案1】:

    来自服务的数据是在渲染之后(在组件以空值渲染之后),所以你需要使用带状态的 promise 来在它准备好后渲染它。

    例子:-

        constructor(){
        super(props);
        this.state={dataIsHere:false};
        }
        dataSource()=>{
        axios.<><><>.then((data)=>this.setState({dataIsHere:true}));
        }
        render(){
        return(
        ...
    //It will render markers once the data is ready
        {this.state.dataIsHere?
        this.state.myMarkers.map((post, index)=> {
                  <MapView.Marker
                    key={post.ID}
                    coordinate={{
                            latitude:{post.lat},
                            longitude:{post.lng}}}
                  />
                         }):null}
        ...
        )
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-12
      • 2021-11-19
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      • 2017-03-26
      相关资源
      最近更新 更多