如何在react-native中单击地图视图上的任何位置时放置标记

时间:2017-04-03 14:34:27

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

我的要求是,我需要在地图视图上显示标记。当用户单击地图视图上的任意位置时,还需要获取放置标记的坐标(纬度和经度)。

我试过的是:

class Maps extends React.Component {
 constructor(props) {
      super(props);
      this.state = {
          region: {
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      },
      marker: {
        latlng:{
         latitude: 17.6868,
         longitude: 83.2185,
          latitudeDelta: LATITUDE_DELTA,
          longitudeDelta: LONGITUDE_DELTA
        }
      }
    };

      }
onMapPress(e) {

  alert("coordinates:"+ JSON.stringify(e.nativeEvent.coordinate))

    this.setState({
      marker: [
        {
          coordinate: e.nativeEvent.coordinate

        },
      ],
    });
  }

  handleMarkerPress(event) {
  const markerID = event.nativeEvent.identifier
  alert(markerID)
}


render() {

    return (
 <MapView identifier={"1"}
                      ref={component => this.map = component}
                      provider={this.props.provider}
                      style={styles.map}
                      region = {this.state.region}
                      onPress={this.onMapPress.bind(this)}
                      //onPress={(event) => this.onMapPress(event)}
                      provider = {PROVIDER_DEFAULT}
                      mapType="standard"
                      zoomEnabled={true}
                      pitchEnabled={true}
                      showsUserLocation={true}
                      followsUserLocation={true}
                      showsCompass={true}
                      showsBuildings={true}
                      showsTraffic={true}
                      showsIndoors={true}>  
                       <MapView.Marker 
                    coordinate={this.state.marker.latlng}

                    />   

                </MapView>
);
}
}

1 个答案:

答案 0 :(得分:3)

首先,为地图标记取一个空数组。

constructor(props) {
  super(props)

  this.state = {
    region: {
      latitude: 24.92009056750823, 
      longitude: 67.1012272143364,
      latitudeDelta: 0.1,
      longitudeDelta: 0.1
    },
    markers: []
  }
}

然后创建一种在地图上添加新标记并返回其坐标的方法

addMarker(coordinates) {
  // Remove the following line after testing, its just to show coordinates as a warning in console.
  console.warn(coordinates);

  this.setState({
    markers: [...this.state.markers, 
      { latlng: coordinates }
    ]
  })
}

最后,在您的MapView中,渲染所有标记

<MapView style={styles.map} region={this.state.region}
      onPress={(e) => this.addMarker(e.nativeEvent.coordinate)}>
  {
    this.state.markers.map((marker, i) => (
      <MapView.Marker key={i} coordinate={marker.latlng} 
           title={marker.latlng.latitude+', '+marker.latlng.longitude} />
    ))
  }
</MapView>

只要您在地图上的任意位置单击,就会在其中放置一个标记。单击标记将显示其坐标作为标题。