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

时间:2019-05-15 04:49:48

标签: react-native react-native-android react-native-maps

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

我尝试过这种方法,但它给出了一个错误“找不到变量:坐标”。

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>
);
  }
}

我如何解决?

2 个答案:

答案 0 :(得分:0)

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

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) }
/>

答案 1 :(得分:0)

我解决了。

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>

);
 }
   }