0

我被困在如何映射 JSON 以响应本机地图。我尝试了几种方法来映射每个坐标来自 API 的 JSON 文件:

{
    "request_time": "2019-09-28T22:13:25+01:00",
    "source": "NaPTAN",
    "acknowledgements": "Contains DfT NaPTAN bus stops data",
    "member": [
        {
            "type": "bus_stop",
            "name": "Western Avenue - SW-bound",
            "description": "Buckingham",
            "latitude": 52.00437,
            "longitude": -0.98989,
            "accuracy": 20,
            "atcocode": "040000004581",
            "distance": 846.0
        },
        {
            "type": "bus_stop",
            "name": "Overn Avenue - NE-bound",
            "description": "Buckingham",
            "latitude": 52.00378,
            "longitude": -0.98884,
            "accuracy": 20,
            "atcocode": "040000002388",
            "distance": 872.0
        }
    ]
}

在此 MapView 部分中,您将看到我正在使用的地图方法,由于某种原因没有显示标记。我收到 TypeError:this.state.markers.map 不是函数:

          <MapView
              style={styles.map}
              showsUserLocation={true}
              initialRegion={{
                  latitude: this.state.latitude,
                  longitude: this.state.longitude,
                  latitudeDelta: 0.0462,
                  longitudeDelta: 0.0261,
          }}
          >

              {this.state.markers.map(marker => (
                  <Marker
                      coordinate={{ latitude: marker.member.latitude, longitude: marker.member.longitude}}
                  />
              ))}

          </MapView>
    );
  }
}

4

3 回答 3

1

根据您的实际代码,进行以下更改

 getBusStops = () => {
    try {
        axios.get(`http://transportapi.com/v3/uk/places.json?lat=${this.state.latitude}&lon=${this.state.longitude}&type=bus_stop&app_id=xxxx&app_key=xxxxxxxx`)
            .then(response => {
                this.setState({ markers: response.data.member});
                console.log(this.state.markers);
            })
            .catch(error => {
                console.log('Error fetching and parsing data', error);
            });
    } catch (error) {
        console.log(error);
    }
}
于 2019-10-01T15:44:57.333 回答
0

this.state.markers.map is not a function意味着您正在尝试在这种情况下map对非数组变量使用函数。this.state.markers

我认为那this.state.markers是第一次渲染的undefined时候,否则请仔细检查 if is an not an 。react native componentthis.state.markersarrayobject

您也可以在渲染之前进行检查,以防undefined.

this.state.markers && this.state.markers.map(marker => ( 
                 <Marker
                      coordinate={{ latitude: marker.member.latitude, longitude: marker.member.longitude}}
                  />
              ))}
于 2019-09-30T21:05:11.413 回答
0

我经历过同样的路障,尝试将 this.state 分配给 const 然后使用 return() 语句停止函数的执行并返回表达式的值。

// 请参见下面的示例。

          
 render() {

    const { markers } = this.state;


    return (
      <View style={styles.container}>
          
          <MapView
              style={styles.map}
              showsUserLocation={true}
              initialRegion={{
                  latitude: this.state.latitude,
                  longitude: this.state.longitude,
                  latitudeDelta: 0.0462,
                  longitudeDelta: 0.0261,
          }}
          >

              {markers.map((marker, index ) => {
                return  (
                  <Marker
                      coordinate={{ latitude: marker.member.latitude, longitude: marker.member.longitude}}
                  />
                  
                  )
              ))}

          </MapView>
    );
  }
}

另外供您参考,这里是一个工作示例的源代码,附有标记如何展开的屏幕截图。在这种情况下,它是一个自定义标记,它从 JSON 中呈现 item.price。

json坐标的格式如下:"geopoints: "55.263237,25.009765","

因此我编写了一个单独的函数来使其兼容。

但是,您可以利用与您的数据结构最兼容的格式。

在此处输入图像描述

componentDidMount() {
        return fetch("www.yourUrlGoesHere.com/Json", { cache: "reload" })
            .then((response) => response.json())
            .then((responseJson) => {
                const mapArray = responseJson.properties.filter((item) => {
                  if (typeof(item.photo) !== 'undefined' && item.photo.length)
                      return item.property_type && item.property_type.toUpperCase();
                });
                this.setState({
                    isLoading: false,
                    dataSource: mapArray
                });
            })
            .catch((error) => {
                console.error(error);
            });
    }


  render() {
    const { navigation } = this.props;
    const { dataSource } = this.state;


    return (
      <View style={styles.container}>

        <MapView initialRegion={{
          latitude: 25.2048,
          longitude: 55.2708,
          latitudeDelta: 0.122,
          longitudeDelta: 0.121
        }} style={styles.map}>
        {dataSource.map((item, index) => {
          return (
            <Marker
              key={`marker-${item.listing_ref}`}
              coordinate = {{
              latitude : item.geopoints.split(",")[1] - 0,
              longitude : item.geopoints.split(",")[0] - 0,
              }}
            >
        
                <View
                  style={[
                    styles.marker,
                    styles.shadow,

                  ]}
                >
                  <Text style={{marginTop: 10, marginBottom: 10,fontSize : 8, fontWeight:"bold", color : "black"}}>د.إ {numeral(item.price).format('0.0a')}</Text>

                </View>
       
            </Marker>
        );
      })}


        </MapView>

      </View>
    );
  }
}

于 2020-03-26T20:16:26.323 回答