如何在地图上放置标记时获取坐标

How to get coordinates when placed the marker on map

我使用 react-native- 创建了地图maps.Now 我需要在点击地图时将纬度和经度作为文本获取。

我试过这种方式,但出现错误"Can't find variable:coordinate"。

export default class Location extends Component {
  constructor(props) {
super(props);
this.state = {
  markers: []
};
this.handlePress = this.handlePress.bind(this);
  }
  handlePress(e) {
this.setState({
  markers: [
    ...this.state.markers,
    {
      coordinate: e.nativeEvent.coordinate,
      key: coordinate,
      color: randomColor()
    }
  ]
});
console.log(e.nativeEvent);
  }
  render() {
return (
  <MapView
    style={styles.map}
    initialRegion={{
      latitude: 7.8731,
      longitude: 80.7718,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421
    }}
    onPress={e => this.handlePress(e)}
  >
    {this.state.markers.map(marker => (
      <Marker
        key={marker.key}
        coordinate={marker.coordinate}
        pinColor={marker.color}
      >
        <View style={styles.marker}>
          <Text style={styles.text}>{marker.coordinate}</Text>
        </View>
      </Marker>
    ))}
  </MapView>
);
  }
}

我该如何解决?

向地图添加一个 onPress 事件。像下面。它将return地图中按下位置的坐标。

onPress={ (event) => console.log(event.nativeEvent.coordinate) }

所以代码将是,

<MapView style = {styles.map}
   initialRegion = {{
      latitude: 7.8731,
      longitude: 80.7718,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421, }}
   onPress={ (event) => console.log(event.nativeEvent.coordinate) }
/>

我解决了

export default class Location extends Component {
  constructor(props) {
  super(props);

   this.state = {
    region: {
     latitude: LATITUDE,
     longitude: LONGITUDE,
     latitudeDelta: LATITUDE_DELTA,
     longitudeDelta: LONGITUDE_DELTA,
    },
    markers: {
      coordinate: {
        latitude: 4,
        longitude: 4,
        },
      key: id,
      color: randomColor(),
    }
   };
  }
  onMapPress(e) {
      this.setState({
         markers: 
         {
            coordinate: e.nativeEvent.coordinate,
            key: id++,
            color: randomColor(),
         },
      });

   SaveAddress=()=>{
     console.log(JSON.stringify(this.state.markers[0].coordinate.latitude))
   }
  }

   render() {
       return (

       <MapView
          provider={this.props.provider}
          style={styles.map}
          initialRegion={this.state.region}
          onPress={e => this.onMapPress(e)}
         >

      <Marker
        key={this.state.markers.key}
        coordinate={this.state.markers.coordinate}
        pinColor={this.state.markers.color}
      >
          <View style={styles.marker}>
          <Text style={styles.text}> 
          {JSON.stringify(this.state.markers.coordinate)}</Text>
        </View>
      </Marker>

  </MapView>

);
 }
   }