在 React Native 中使用地图功能

Using the map function in React Native

我正在尝试在 MapView 上为存储在我的状态数组中称为标记的每个位置呈现标记,但由于某种原因,当我尝试在地图函数中引用状态时,我得到了未定义。我检查了语法错误,但找不到问题所在。基本上每次用户更改 his/her 位置时,我都想将他们的标记设置到他们的新位置。尝试在 render() 函数内使用 map 函数时发生错误。我在下面张贴了错误的图片。

import React, {Component} from 'react';
import {AppRegistry,Text,View,StyleSheet} from 'react-native'
import Component1 from`enter code here` './Component1'
import Component3 from './Component3'
import Component4 from './Component4'
import MapView from 'react-native-maps'

export default class myapp extends Component{
  constructor(props){
    super();
    this.state ={
      markers: [
        {
          watchId: 0,
          latitude:3,
          longitude:2
        },
        {
          watchId: 2,
          latitude:3,
          longitude:2
        }
      ]

    }
  }

  componentDidMount(){
    navigator.geolocation.watchPosition((position)=>{
      var lat = parseFloat(position.coords.latitude)
      var long = parseFloat(position.coords.longitude)
      var id = parseFloat(position.coords.watchId)
      var found = false
      this.setState({markers: this.state.markers.map(marker =>{
        if(marker.watchId === id){
          found = true
          marker.latitude = lat
          marker.longitude = long
        }
      })});
    if(found === false){
      this.setState({markers:[{watchId:id,latitude:lat,longitude:long}]});
    }
    },null,{timeout:0,distanceFilter:0})
}
  render(){
    return(
      <View>
      <MapView style={{height:350,width:350,marginTop:300,alignSelf:'center'}}
      initialRegion={{
        latitude: 37.33,
        longitude: -121.4024,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
      }}
      showsUserLocation={true}
      followsUserLocation={true}
      showsMyLocationButton={true}
      >
      {this.state.markers.map(marker =>{
        return(
                <MapView.Marker
                coordinate={{latitude:marker.latitude,longitude:marker.longitude}}
                title={"title"}
                description={"description ey"}

             />
        );
      })}

      </MapView>
      </View>

    );
  }
}
AppRegistry.registerComponent('myapp',()=>myapp);

您需要 return componentDidMount 中的标记。

例如:

 this.setState({markers: this.state.markers.map(marker =>{
    if(marker.watchId === id){
      found = true
      marker.latitude = lat
      marker.longitude = long
    }
    return marker
  })});